3

Given a Spring Boot Maven Project with this structure:

src main resources static file.txt 

This gets packaged into a jar file:

static file.txt 

I have tried the following ways to try to read file.txt:

File file = ResourceUtils.getFile("file.txt"); File file = ResourceUtils.getFile("/file.txt"); File file = ResourceUtils.getFile("static/file.txt"); File file = ResourceUtils.getFile("/static/file.txt"); 

None of these work.

1 Answer 1

4

It's a resource. Packaged inside a jar file. A File represents a path on the file system. So it can't represent an entry of a jar file.

Use MyClass.class.getResourceAsStream("/static/file.txt"). That uses the class loader, and thus loads resources from all the directories and jar files in the classpath.

Sign up to request clarification or add additional context in comments.

2 Comments

My first approach was to use servletContext.getResourceAsStream("/static/file.txt") which does not work. But using your approach does. Any idea why?
Add to add to the mystery, in a non-Boot Spring MVC app, servletContext works, but the class loader does not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.