Paul Croarkin
Paul Croarkin

Reputation: 14675

Cannot read Resource from /static folder in Spring Boot

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.

Upvotes: 3

Views: 3242

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

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.

Upvotes: 4

Related Questions