Contents

Reading a file in Java

Writen by: David Vlijmincx

Introduction

In this post, we will look at three different ways to read a file in Java. All the examples in this post use Java 8 to take advantage of NIO and streams.

Every example reads the same text file located at /home/david/test.txt. The file's content is “Hello, Java developer!” without quotes.

NewBufferdReader to read a file line by line

The newBufferedReader reads a file efficiently, which is great for big files. In the following example, we pass a path parameter to Files.newBufferedReader(path). Using a while loop, we read the current line into a temporary variable and print it inside the loop. The while loop will run till it reaches the end of the file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Path path = Path.of("/home/david/test.txt");
try(BufferedReader reader = Files.newBufferedReader(path)){
    // temporary variable to hold the current line
    String tempLine = null;

    // loop over the lines inside the file till there
    // are no lines left
    while ((tempLine = reader.readLine()) != null){
        System.out.println("tempLine = " + tempLine);
    }

    // newBufferedReader() may throw an exception
} catch (IOException e) {
    System.out.println("An exception happened when reading the file");
    throw new RuntimeException(e);
}

ReadAllLines() to read all lines in a file

Using readAllLines we can read all the lines of the file at once. This works great for smaller files that fit into memory. In the following example, we read all the lines of the file using Files.readAllLines(path) into a list of strings. Each entry inside the list represents one line of the file.

In the for-loop, the content of the list is printed to the console.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Path path = Path.of("/home/david/test.txt");
try {
    List<String> strings = Files.readAllLines(path);

    for (String line: strings) {
        System.out.println("line = " + line);
    }

    // readAllLines(path) may throw an exception
} catch (IOException e) {
    throw new RuntimeException(e);
}

Read a file as Stream

Using Java 8, we can also leverage streams while reading a file. We can use this, for example, to map each line to a different result. In the following example, we read a file line-by-line by creating a stream inside a try-with-resource statement like this Stream<String> lines = Files.lines(path).

On line 4, we create a stream object to read the lines, and on line 7, we change the result of each line by adding “read: " to the beginning of each line.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
Path path = Path.of("/home/david/test.txt");

// Create Stream to read the lines from a file
try (Stream<String> lines = Files.lines(path)){
    
    List<String> strings = lines
            .map(line -> "read: " + line) // add "read:" to each lines
            .collect(Collectors.toList());

    for (String line: strings) {
        System.out.println("line = " + line);
    }

    // readAllLines(path) may throw an exception
} catch (IOException e) {
    throw new RuntimeException(e);
}

Conclusion

In this quick post, we looked at three different ways to read a file in Java. We used newBufferedReader to read a big file efficiently. We also used ReadAllLines(), which is great for smaller files that fit into memory. The latest example showed to can leverage steams to read a file and map each line into a new result.

 




Questions, comments, concerns?

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