English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to get the file name from the absolute path in Java.
import java.io.File; class Main { public static void main(String[] args) { //Linked to the file Test.class File file = new File("C:\\Users\\Bhandari\\Desktop\\w3codebox\\Java Article\\Test.class"); //Get the file name using getName() String fileName = file.getName(); System.out.println("File Name: ", + fileName); } }
Output Result
File Name: Test.class
In the above example, we used the getName() method of the File class to get the file name.
To learn more about files, please visitJava File.
We can also use string methods to get the file name from the absolute path of the file.
import java.io.File; class Main { public static void main(String[] args) { File file = new File("C:\\Users\\Bhandari\\Desktop\\w3codebox\\Java Article\\Test.class"); //Convert the file to a string string String stringFile = file.toString(); int index = stringFile.lastIndexOf('\\'); if(index > 0) { String fileName = stringFile.substring(index + 1); System.out.println("File Name: ", + fileName); } } }
Output Result
File Name: Test.class
In the above example,
file.toString() - Converts a File object to a string.
stringFile.lastIndexOf() -Returns the last occurrence of the character '\' in stringFile. For more information, please visitJava String lastIndexOf().
stringFile.substring(index +1) - Return Positionindex +1All subsequent substrings. For more information, please visitJava String substring().