You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅获取PDF文件名?高校开发项目中的实现需求

获取PDF文件名(不含路径)的简便Java方法

嗨,我之前做项目时也遇到过一模一样的需求!给你几个靠谱又简便的方法,完全能实现你想要的类似file.getName()的功能:

方法一:用传统File类(最直接)

如果你已经持有PDF文件的File对象,直接调用它的getName()方法就能拿到纯文件名,自动忽略前面的完整路径:

// 假设你已经实例化了PDF文件的File对象
File pdfFile = new File("D:/university-project/output/student-score-report.pdf");
String pdfFileName = pdfFile.getName(); 
// 结果就是 "student-score-report.pdf"

哪怕你只有路径字符串,也可以先转成File对象再调用:

String pdfPath = "D:/university-project/output/student-score-report.pdf";
String pdfFileName = new File(pdfPath).getName();

方法二:用Java NIO的Path类(推荐,Java 7+)

这是Java官方更推荐的现代路径处理方式,跨平台兼容性更好,用法也很简洁:

// 从路径字符串生成Path对象
Path pdfPath = Paths.get("D:/university-project/output/student-score-report.pdf");
String pdfFileName = pdfPath.getFileName().toString();
// 同样得到 "student-score-report.pdf"

如果是从已有的File对象转过来也很方便:

File pdfFile = new File("D:/university-project/output/student-score-report.pdf");
String pdfFileName = pdfFile.toPath().getFileName().toString();

不推荐的手动字符串分割

虽然可以用lastIndexOf()手动截取文件名,但不同系统的路径分隔符不一样(Windows是\,Linux/macOS是/),容易出现跨平台问题,除非你专门处理分隔符,否则还是用上面的API更稳妥:

// 仅作参考,不推荐在项目中使用
String pdfPath = "D:/university-project/output/student-score-report.pdf";
String fileName = pdfPath.substring(pdfPath.lastIndexOf(File.separator) + 1);

总结一下,优先用Path类的getFileName()方法,或者直接用File.getName(),都是现成的简便方法,完全满足你只展示PDF文件名的需求~

内容的提问来源于stack exchange,提问作者Francisco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:32:20