字符串变量包含一个文件名,C:\Hello\AnotherFolder\The file name . pdf。我如何只得到文件名文件名。pdf作为字符串?
我计划拆分字符串,但这不是最佳解决方案。
字符串变量包含一个文件名,C:\Hello\AnotherFolder\The file name . pdf。我如何只得到文件名文件名。pdf作为字符串?
我计划拆分字符串,但这不是最佳解决方案。
当前回答
只需使用File.getName()
File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());
使用String方法:
File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+1));
其他回答
java.nio.file.Path的getFileName()方法,用于返回该路径对象所指向的文件或目录的名称。
Path getFileName ()
供参考:
https://www.geeksforgeeks.org/path-getfilename-method-in-java-with-examples/
只需使用File.getName()
File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());
使用String方法:
File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+1));
您可以使用FileInfo对象来获取文件的所有信息。
FileInfo f = new FileInfo(@"C:\Hello\AnotherFolder\The File Name.PDF");
MessageBox.Show(f.Name);
MessageBox.Show(f.FullName);
MessageBox.Show(f.Extension );
MessageBox.Show(f.DirectoryName);
在Apache Commons IO中使用FilenameUtils:
String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
考虑Java是多平台的情况:
int lastPath = fileName.lastIndexOf(File.separator);
if (lastPath!=-1){
fileName = fileName.substring(lastPath+1);
}