Read a file from resources directory

Writen by: David Vlijmincx

There comes a time when you need to read a file from the resource folder of your project. You could have a file you want to read in the src/main/resources or src/test/resources directory. In this tutorial, I am going to show you how to read a file from your production or testing code.

Using NIO files

The most straightforward way to read a file is to the files belonging to the NIO (New Input/Output) package. These classes are non-blocking which is great when reading files. In the following example, a file is read from the src/test/resources/ directory inside the project.

Path path = Path.of("src/test/resources/myTestFile.txt");

// Create a list of lines
List<String> lines = Files.readAllLines(path);

// read as everything into a single string
String text = Files.readString(path);
System.out.println("text = " + text);

The path specifies where the file is located. The path instance can then be used as a parameter for the Files.readAllLines or Files.readString method. The readAllLines returns a list of string from the file, while the readString reads the entire file into a single string instance.

Using Classloader

You can also use the classloader to read a file. While the path is easier to write the rest of the code is less straightforward. The first example is also much more preferred.

InputStream resource = this.getClass().getClassLoader().getResourceAsStream("myTestFile.txt");

List<String> lines = new BufferedReader(new InputStreamReader(resource)).lines().toList();

The previous example creates an InputStream using the classloader. The file you want to read is specified inside the getResourceAsStream() method as a parameter. To read a text file with an InputStream you need to create a BufferedReader that can read the lines from the file.


In this quick post, I showed you two common ways to read a file from a resource directory inside your project. Both of these methods can be used to read a file from the src/test/resources and or src/main/resources directories or of course any other directory you have access to.


Questions, comments, concerns?

Have a question or comment about the content? Feel free to reach out!