字符串变量包含一个文件名,C:\Hello\AnotherFolder\The file name . pdf。我如何只得到文件名文件名。pdf作为字符串?
我计划拆分字符串,但这不是最佳解决方案。
字符串变量包含一个文件名,C:\Hello\AnotherFolder\The file name . pdf。我如何只得到文件名文件名。pdf作为字符串?
我计划拆分字符串,但这不是最佳解决方案。
当前回答
你可以使用path = C:\Hello\AnotherFolder\TheFileName.PDF
String strPath = path.substring(path.lastIndexOf("\\")+1, path.length());
其他回答
你可以使用path = C:\Hello\AnotherFolder\TheFileName.PDF
String strPath = path.substring(path.lastIndexOf("\\")+1, path.length());
考虑Java是多平台的情况:
int lastPath = fileName.lastIndexOf(File.separator);
if (lastPath!=-1){
fileName = fileName.substring(lastPath+1);
}
自1.7年
Path p = Paths.get("c:\\temp\\1.txt");
String fileName = p.getFileName().toString();
String directory = p.getParent().toString();
您可以使用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);
使用Path (Java 7+)的替代方法:
Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();
注意,在\\上拆分字符串取决于平台,因为文件分隔符可能不同。路径#getName为您解决了这个问题。