How to Read a File from Resources Folder in Java

1. Introduction

When you build a java project and pack it into a jar (or a war), the files under the resources folder are included into the jar. These files may include configuration files, scripts and other resources needed during run time. When the software is executed, it may need to load the contents of these files for some kind of processing — may be properties, sql statements, etc. In this article, we show you how to load these resources when the program is running.

2. Packaging Resources

Check out the directory hierarchy below:

Maven packs all the files and folders under main/resources into the jar file at the the root. You can access these files and folders from your java code as shown below.

3. Loading the Resources

The following code snippet shows how to load resources packed thus into the jar or war file:

String respath = "/poems/Frost.txt";
InputStream in = sample2.class.getResourceAsStream(respath);
if ( in == null )
    throw new Exception("resource not found: " + respath);

Using the method Class.getResourceAsStream(String), you can get an InputStream to read the resource. The method returns null if the resource cannot be found or loaded.

To read binary resources, you can use directly use the InputStream instance. For reading a text resource, you can convert it to a Reader instance, possibly specifying the character encoding:

InputStreamReader inr = new InputStreamReader(in, "UTF-8");
int len;
char cbuf[] = new char[2048];
while ((len = inr.read(cbuf, 0, cbuf.length)) != -1) {
    // do something with cbuf
}

4. Using Absolute Path of Resource

To load a resource whose full path from the root of the jar file is known, use the full path starting with a “/“.

InputStream in = sample1.class.getResourceAsStream("/poems/Frost.txt");

5. Loading from Relative Paths

When you use a relative path (not starting with a “/“) to load a resource, it loaded relative to the class from which getResourceAsStream() is invoked. For example, to load “app.properties” relative to the invoking class, do not start the path with a “/“.

InputStream in = sample1.class.getResourceAsStream("app.properties");

Conclusion

In this article, we demonstrated how to use the Class.getResourceAsStream() method to load resources from the jar file or war file. An absolute resource path is resolved from the root of the jar file while a relative paths is resolved with respect to the loading class.