我正在尝试使用Spring资源加载器读取文本文件,如下所示:
Resource resource = resourceLoader.getResource("classpath:\\static\\Sample.txt");
该文件位于我的Spring启动项目中:
它在eclipse中运行应用程序时工作正常,但是当我打包应用程序然后使用java -jar运行它时,我得到文件未找到异常:
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
有谁可以帮助我吗 ?
提前致谢!
4 回答
我遇到了同样的问题,正如@Gipple Lake解释的那样,使用Spring启动时,您需要将文件作为inputStream加载 . 下面我将添加我的代码作为示例,我想读取import.xml文件
我添加了“
imports.xml
”吼叫src/main/ressources/imports
请尝试
resourceLoader.getResource("classpath:static/Sample.txt");
使用
java -jar XXXX.jar
运行时使用此代码------更新------
在完成您的代码之后,问题是您尝试通过
FileInputStream
读取文件,但实际上它在jar文件中 .但实际上你得到
org.springframework.core.io.Resource
所以意味着你得到了InputStream,所以你可以像new BufferedReader(new InputStreamReader(resource.getInputStream())).readLine();
那样做将文件放在 resources/static 下,它将在类路径中并读取如下所示的路径
我已经检查了你的代码 . 如果你想在Spring Boot JAR中从classpath加载一个文件,那么你必须使用 resource.getInputStream() 而不是 resource.getFile() . 如果你尝试使用resource.getFile(),你将收到一个错误,因为Spring尝试访问文件系统路径,但无法访问JAR中的路径 .
详情如下:
https://smarterco.de/java-load-file-classpath-spring-boot/