Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - Reading Text File using ResourceLoader

I’m trying to read a text file using Spring resource loader like this :

Resource resource  = resourceLoader.getResource("classpath:\\static\\Sample.txt");

The file locates here in my Spring boot project: enter image description here

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

I unziped the Jar file the Sample locates in : XXX-0.0.1-SNAPSHOT\BOOT-INF\classes\static\Sample.txt

Can someone help me please ?

Thanks in advance!

like image 885
Greg Avatar asked Jan 20 '17 01:01

Greg


People also ask

What is @resource annotation in spring boot?

The @Resource annotation is used to identify a class, field, or method that upon initialization, the resource will be injected. For a class-based @Resource, the "resource is looked up by the application at runtime".

How do I read a classpath file?

xml from it, firstly we need to add resource folder to classpath and then read it. Here we used getClass(). getResource(), this method is trying to read our file example. xml from the root "/" path of the classpath.


1 Answers

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.

detail as below:

https://smarterco.de/java-load-file-classpath-spring-boot/

like image 66
Gipple Lake Avatar answered Sep 20 '22 15:09

Gipple Lake