Java read file line by line

In this post, we will see different ways to read file line by line in java.

Sometimes, we need to read file line by line to a String, and process it.

Here are different ways to read file line by line in java.

Java 8 Streams

Java 8 has introduced a new method called lines() in Files class which can be used to read file line by line.

The advantage of using this approach is that it will return Stream of String which will be populated lazily as Stream is used. In case, you need to read the large file and require only first 1000 lines to read, then this is the best approach as it will not rest of the file in memory which will result in better throughput.

Another advantage is that you can use different Stream methods to perform the operation on Stream such as filter, map, etc.

Let’s see this with the help of an example.

Let’s say you want print all male employees.You can use filter method to filter all the male employees.

Using BufferReader

You can use java.io.BufferReader‘s readLine() method to read file into String line by line.Once you reach end of the file, it will return null.

Using Scanner

You can use java.util.Scanner class to read file line by line. You can use hasNextLine() method to check if there are more lines to read and nextLine() to retrieve current line and move the read position to next line.

Scanner class divides its input into token using delimiter, which is either line feed("\n") or carriage return("\r".) in our case.

Using Files

You can use java.nio.file.File ‘s readAllLines method to read file into list of String.

It may not perform well in case you have large file.

Using RandomAccessFile

You can also use RandomAccessFile's readLine() method to read file line by line in java. You need to open file in read mode and then call readLine() method to read file line by line.

Using Apache Commons

In case you prefer to use Apache commons library, you can use FileUtils‘s readLines method to read file into the list.

You need to include following dependencies in pom.xml.

Please note that this approach may not be well optimized. It will read the complete file into a list which can perform badly in case of large files.

That’s all about how to read file line by line in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *