Java

Read a File from Resources Folder in Java

This tutorial illustrates How to read a file from Classpath or Resources Folder in Java with practical examples using File IO, NIO, and FileChannel.

Overview

In the next sections we will explain how to read a file which is placed src/main/resources (Resources) directory. There are many ways to read a file from Classpath in Java. They are based on Java File IO, Java NIO, and Java File Channels. We will cover all of them one in this tutorial.

Using Java getResourceAsStream()

This is an example of using getResourceAsStream method to read a file from src/main/resources directory.

try ( InputStream inputStream = this.getClass().getResourceAsStream("/file.txt"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); Stream<String> lines = bufferedReader.lines(); ) { lines.forEach(System.out::println); }
Code language: Java (java)

First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream. Then, we wrap the input stream reader into a BufferedReader instance.

The lines method on the BufferedReader class returns a Stream of Strings which are lazily read from the file. We are then printing each line from the file on the console.

Note that, in Java File IO we need explicitly close all of the streams and readers that we create. Also, the Java 8 Streams which are generated from File IO resources need to be closed. To do that, we are using a try-with-resources block to instantiate them.

Alternatively, we can use getResourceAsStream on the class loader.

InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("file.txt");
Code language: Java (java)

The difference between the two is that when we use getResourceAsStream on the class the path is relative to current directory. Thus, we added a slash (/) to the path. On the other hand getResourceAsStream on the class loader instance takes absolute path. Which is why we have not added the slash (/).

Using FileReader

We can use BufferedReader by wrapping a FileReader to read contents of a file. Next, is an example of using BufferedReader to read file from Classpath.

try ( FileReader fileReader = new FileReader("src/main/resources/file.txt"); BufferedReader bufferedReader = new BufferedReader(fileReader); Stream<String> lines = bufferedReader.lines(); ) { lines.forEach(System.out::println); }
Code language: Java (java)

Here we are creating an instance of FileReader by providing the path to file. Next, we create an Instance of BufferedReader upon the file reader. Finally, as seen in the previous example we create a Stream of lines from the buffered reader to print them on the console.

Using Files.newBufferedReader()

Next is how to use Files.newBufferedReader to read a file from resources directory. It is useful when we want to read files of large size.

try ( BufferedReader bufferedReader = Files.newBufferedReader( Paths.get("src/main/resources/file.txt") ); Stream<String> lines = bufferedReader.lines(); ) { lines.forEach(System.out::println); }
Code language: Java (java)

Using Files.lines()

The Java Files class provides lines() method, which is one more handy abstraction to avoid the boilerplate code. Next is an example of how to read a Classpath resource line by line. Note that we are also providing UTF-8 Charset.

try ( Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8) ) { lines.forEach(System.out::println); }
Code language: Java (java)

The try-with-catch resource block ensures that the respective streams are closed when the block ends.

Using DataInputStream

Next, we will cover an example of using DataInputStream to read data from a file in src/main/resources directory. The DataInputStream is useful for reading primitive java data types from a file.

try ( InputStream inputStream = this.getClass().getResourceAsStream("/file.txt"); DataInputStream dataInputStream = new DataInputStream(inputStream); ) { int numBytesRead; if ((numBytesRead = dataInputStream.available()) > 0) { byte[] bucket = new byte[numBytesRead]; dataInputStream.read(bucket); System.out.println(new String(bucket)); } }
Code language: Java (java)

Using FileChannel

Finally, we will see an example of using FileChannel to read file in resources directory. This is the fasted way of reading data from a file, especially when we are dealing with large files.

Path path = Path.of(this.getClass().getResource("/file.txt").toURI()); try ( RandomAccessFile randomAccessFile = new RandomAccessFile(path.toFile(), "r"); FileChannel fileChannel = randomAccessFile.getChannel(); ) { int bucketSize = 1024; ByteBuffer byteBuffer = ByteBuffer.allocate(bucketSize); fileChannel.read(byteBuffer); byteBuffer.flip(); System.out.println(new String(byteBuffer.array())); }
Code language: Java (java)

First, we create a Path from the resource file, and use it to instantiate a RandomAccessFile. The RandomAccessFile then provides the FileChannel.

Summary

In this detailed tutorial we have covered different ways of reading a file from src/main/resources folder in plain Java. We leaned that we can use current Class or a ClassLoader to read the file from resources folder as a Stream.

Also, we learnt a different ways of reading data from the file, along with examples of Java NIO and FileChannel abstractions. We also, learned it is important to close all of the File IO Streams and readers and we can use try-with-resources block to do that automatically. For more on Java, Please visit: Java Tutorials.