示例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()
方法获取File
的名称。
示例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()。