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 boot 项目中:
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
我解压了示例所在的 Jar 文件:XXX-0.0.1-SNAPSHOTBOOT-INFclassesstaticSample.txt
I unziped the Jar file the Sample locates in : XXX-0.0.1-SNAPSHOTBOOT-INFclassesstaticSample.txt
有人可以帮我吗?
提前致谢!
推荐答案
我已经检查了您的代码.如果您想从 Spring Boot JAR 中的类路径加载文件,那么您必须使用 资源.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屋!