Spring Boot - 使用ResourceLoader读取文本文件 [英] Spring Boot - Reading Text File using ResourceLoader
问题描述
我正在尝试使用Spring资源加载器读取文本文件,如下所示:
I’m trying to read a text file using Spring resource loader like this :
Resource resource = resourceLoader.getResource("classpath:\\static\\Sample.txt");
该文件位于我的Spring启动项目中:
The file locates here in my Spring boot project:
在eclipse中运行应用程序时工作正常,但是当我打包应用程序然后使用java -jar运行它时,我得到文件未找到异常:
It works fine when running the application in eclipse, but when I package the application then run it using java –jar , I get file not found exception :
java.io.FileNotFoundException: class path resource [static/Sample.txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/workspace-test/XXX/target/XXX-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static/Sample.txt
我解压了Sample所在的Jar文件:
XXX-0.0.1-SNAPSHOT \ BOOT-INF \classes \ static \Sample.txt
I unziped the Jar file the Sample locates in : XXX-0.0.1-SNAPSHOT\BOOT-INF\classes\static\Sample.txt
有人可以帮我吗?
提前致谢!
推荐答案
我已经检查了你的代码。如果你想在Spring Boot JAR中从classpath加载一个文件,那么你必须使用 resource.getInputStream()而不是 resource.getFile() 。如果您尝试使用resource.getFile(),您将收到错误,因为Spring尝试访问文件系统路径,但无法访问JAR中的路径。
I have checked your code.If you would like to load a file from classpath in a Spring Boot JAR, then you have to use the resource.getInputStream() rather than resource.getFile().If you try to use resource.getFile() you will receive an error, because Spring tries to access a file system path, but it can not access a path in your JAR.
详情如下:
https://smarterco.de/java-load-file-classpath-spring-boot/
这篇关于Spring Boot - 使用ResourceLoader读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!