springboot打成jar后获取classpath下文件失败

本文介绍了解决SpringBoot项目中,打包成JAR后无法通过文件系统路径读取classpath资源的问题。提供了正确的资源读取方式,并附带错误示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springboot打成jar后获取classpath下文件失败

使用如下代码:

ClassPathResource resource = new ClassPathResource("application.yml");
File file = resource.getFile();
FileUtils.readLines(file).forEach(System.out::println);

未打包时可以获取到文件,打包后报错

Caused by: java.io.FileNotFoundException: class path resource [application.yml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/sunmnet/JetBrains/workspace/bigdata-parse-table/target/bigdata-parse-table-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/application.yml
        at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:215) ~[spring-core-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:53) ~[spring-core-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at hello.whz.Application.lambda$lookup$0(Application.java:30) [classes!/:1.0-SNAPSHOT]
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) [spring-boot-1.5.8.RELEASE.jar!/:1.5.8.RELEASE]
        ... 14 common frames omitted

这是因为打包后Spring试图访问文件系统路径,但无法访问JAR中的路径。
因此必须使用resource.getInputStream()

ClassPathResource resource = new ClassPathResource("application.yml");
InputStream inputStream = resource.getInputStream();
IOUtils.readLines(inputStream).forEach(System.out::println);

参考https://smarterco.de/java-load-file-from-classpath-in-spring-boot/

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值