字符串变量包含一个文件名,C:\Hello\AnotherFolder\The file name . pdf。我如何只得到文件名文件名。pdf作为字符串?
我计划拆分字符串,但这不是最佳解决方案。
字符串变量包含一个文件名,C:\Hello\AnotherFolder\The file name . pdf。我如何只得到文件名文件名。pdf作为字符串?
我计划拆分字符串,但这不是最佳解决方案。
当前回答
java.nio.file.Path的getFileName()方法,用于返回该路径对象所指向的文件或目录的名称。
Path getFileName ()
供参考:
https://www.geeksforgeeks.org/path-getfilename-method-in-java-with-examples/
其他回答
这个答案在c#中适用于我:
using System.IO;
string fileName = Path.GetFileName("C:\Hello\AnotherFolder\The File Name.PDF");
使用Path (Java 7+)的替代方法:
Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();
注意,在\\上拆分字符串取决于平台,因为文件分隔符可能不同。路径#getName为您解决了这个问题。
你可以使用path = C:\Hello\AnotherFolder\TheFileName.PDF
String strPath = path.substring(path.lastIndexOf("\\")+1, path.length());
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));