Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 832
Paul Croarkin Avatar asked Dec 22 '25 03:12

Paul Croarkin


1 Answers

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.

like image 126
JB Nizet Avatar answered Dec 23 '25 20:12

JB Nizet