4

I didn't manage to access any classpath files in my spring-boot jar.

I tried the following :

Resource resource = new ClassPathResource("myResourceFile"); 

But when I tried to read it, I got the following message

it does not reside in the file system: jar:file:/myjar.jar!/BOOT-INF/classes!/myResourceFile 

I noticed the 2 exclamation marks. The first is to indicate the resource is inside a jar, but I don't know if the second one (after classes) is involved in my problem.

Thanks for your help.

I use spring-boot 1.4.5 and spring-* 4.3.7.

3 Answers 3

2

If you need to load an image from classpath , you can use something like below:

new ClassPathResource("/static/img/logo.png"); 

Resource Path:

main -> resources -> static.img -> logo.png 
Sign up to request clarification or add additional context in comments.

Comments

1

The proper way to read a classpath resource is by getting the resource as stream.

This might fix your issue:

InputStream is = this.getClass().getResourceAsStream("/myResourceFile"); 

2 Comments

Thanks for your help. Indeed I can read a file inside my executable spring-boot jar with InputStream. The problem is I only know the folder name, and I do not manage to list file inside my folder with InputStream. Any idea?
I don't think you can list files inside a resource folder (as a rule of thumb, resource files should be static). If you want to do it anyway then you will need to create a separate fixed file that lists all the files in your resource directory.
0

I host a Spring Boot application in Docker on my VPS. This code will work on a local system whilst developing in an IDE as well as if the .JAR-file is wrapped in a Docker image:

Example case:

I like to get a PDF. The PDf document is located at static/docs/not-a-porn.PDF.

1.) Wire the class ResourceLoader

private final ResourceLoader resourceLoader; public MyService(@Autowired ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } 

2.) Create a resource by pathOfAttachment (String)

String pathOfAttachment = "classpath:static/docs/not-a-porn.PDF" Resource resource = this.resourceLoader.getResource(pathOfAttachment); 

Resource is an interface that extends InputStreamSource as you can see in the documentation:

public interface Resource extends InputStreamSource

Source: org.springframework.core.io Link to documentation (click here)

3.) Get file

String fileName = resource.getFilename(); File file = resource.getFile(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.