How do I get the file name from a String containing the Absolute file path?

To get the file name from a String containing the absolute file path in Java, you can use the following methods:

  1. Using the File class:
String filePath = "/path/to/file.txt";
File file = new File(filePath);
String fileName = file.getName();  // fileName is "file.txt"
  1. Using the substring() method of the String class:
String filePath = "/path/to/file.txt";
int lastSlashIndex = filePath.lastIndexOf('/');
String fileName = filePath.substring(lastSlashIndex + 1);  // fileName is "file.txt"
  1. Using the split() method of the String class:
String filePath = "/path/to/file.txt";
String[] parts = filePath.split("/");
String fileName = parts[parts.length - 1];  // fileName is "file.txt"

Keep in mind that these methods will only work for file paths with forward slashes (/). If the file path uses backslashes (), you will need to use a different delimiter when splitting the string.