Spring Boot: How to read a file from the resources folder

While it’s easy to read a file by simply using its absolute path during development on your machine, it’s a different story after you package your application into a JAR and deploy it on a production server.

The problem is that when you package your application, you can no longer access the files inside the source. It makes sense, because all of it was packaged in a JAR, thus all paths that are pointing to files inside of the JAR also become invalid.

Luckily, you can make your life much easier by keeping your file in your “resources” folder and accessing it by using ClassPathResource.

For instance, if you put a file called “instructions.txt” in your resources folder, you can get access to its content like so:

import org.springframework.util.FileCopyUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

// ...

InputStream is = new ClassPathResource("/instructions.txt").getInputStream();
try {
    String contents = new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8);
    System.out.println(contents);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (is != null) {
        is.close();
    }
}

Note that by resources folder, I mean the one in Maven’s standard layout structure (src/main/resources).

Resources folder in IntelliJ IDEA

The main advantage is, of course, the fact that your files are packaged inside the JAR and no matter where you deploy your application, they will still be accessible.

I’m also assuming you understand that since those resources are packaged with your application, it will also increase the size of your JAR, so while it can be useful for images, you might want to rethink your strategy if you planned on leaving your movie collection in your resource folder…