springboot打成jar后获取classpath下文件失败
原文链接:https://blog.csdn.net/qq_18748427/article/details/78606432
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);
分类:
springboot
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤