示例 1: 使用 getName() 从绝对路径获取文件名
import java.io.File; class Main { public static void main(String[] args) { // link to file Test.class File file = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Programiz\\Java Article\\Test.class"); // get file name using getName() String fileName = file.getName(); System.out.println("File Name: " + fileName); } }
输出
File Name: Test.class
在上面的例子中,我们使用了
File
类的
getName()
方法来获取文件名。
示例2: 使用字符串方法获取文件名
我们还可以使用字符串方法从绝对路径中获取文件名。
import java.io.File; class Main { public static void main(String[] args) { File file = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Programiz\\Java Article\\Test.class"); // convert the file into the string String stringFile = file.toString(); int index = stringFile.lastIndexOf('\\'); if(index > 0) { String fileName = stringFile.substring(index + 1); System.out.println("File Name: " + fileName); } } }
输出
File Name: Test.class
在上面的例子中,
file.toString()-将 File
对象转换为字符串。
stringFile.lastIndexOf()-返回 stringFile 中最后一次出现的字符 '\\'。要了解更多信息,请访问 Java String lastindexOf()。
stringFile.substring(index + 1)-返回位置 index + 1 之后的所有子字符串。要了解更多信息,请访问 Java String substring()。