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.
|
|
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.
|
|
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.
|
|
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.