Spring Boot中如何读取resources目录下的文件
在Java编码过程中,我们常常希望读取项目内的配置文件,按照Maven的习惯,这些文件一般放在项目的src/main/resources下。因此,我们把合同的PDF模板存放于resources/template/test.pdf,以作测试用例,下面提供两种读取方式,它们分别在windows和Linux环境(linux下jar包)都可以正常运行。
方法一 ClassPathResource
String pdfFilePath = "template/test.pdf";
Resource resource = new ClassPathResource(pdfFilePath);
通过如下方法可以转Resource换成InputStream :
InputStream is = resource.getInputStream();
方法二 getContextClassLoader
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pdfFilePath);
测试用例
public static void main(String[] args) {
try {
String pdfFilePath = "template/test.pdf";
Resource resource = new ClassPathResource(pdfFilePath);
System.out.println( resource.getURI() + " -- ****** path = ");
if (resource.isReadable()) {
//每次都会打开一个新的流
InputStream is = resource.getInputStream();
System.out.println("方法一 " + is.available());
}
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pdfFilePath);
System.out.println("方法二 " + inputStream.available());
} catch (IOException e) {
e.printStackTrace();
}
}
如果有其它读取的办法,欢迎留言。
读后有收获,小礼物走一走,请作者喝咖啡。

作者:楼兰胡杨
本文版权归作者和博客园共有,欢迎转载,但请注明原文链接,并保留此段声明,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
2019-01-18 使用Eclipse进行远程调试