字符串变量包含一个文件名,C:\Hello\AnotherFolder\The file name . pdf。我如何只得到文件名文件名。pdf作为字符串?

我计划拆分字符串,但这不是最佳解决方案。


当前回答

您可以使用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);

其他回答

您可以使用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);

其他答案不太适合我的特定场景,我正在读取来自不同于当前操作系统的路径。为了详细说明,我将从Windows平台保存的电子邮件附件保存在Linux服务器上。JavaMail API返回的文件名类似于'C:\temp\hello.xls'

我最终得出的解决方案是:

String filenameWithPath = "C:\\temp\\hello.xls";
String[] tokens = filenameWithPath.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];

你可以使用path = C:\Hello\AnotherFolder\TheFileName.PDF

String strPath = path.substring(path.lastIndexOf("\\")+1, path.length());

在Apache Commons IO中使用FilenameUtils:

String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");

使用Path (Java 7+)的替代方法:

Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();

注意,在\\上拆分字符串取决于平台,因为文件分隔符可能不同。路径#getName为您解决了这个问题。