How To Read a Line By Line From a File in Java

It’s a common task in Java to read a text file line by line.

If you want to read a specific line in a file you should read each line anyway until you will find what you need.

In this article, I want to show 3 ways how to read string lines from the file in Java.

Keep reading…

3 Ways How To Read File Line by Line in Java

Java provides at least 3 ways how to read strings from file: FileReader + BufferedReader, Files.readLines, and Scanner.

Let’s take a deeper look.

FileReader + BufferedReader

FileReader is a class for reading character files.

It makes a read operation for each character in the file.

That’s why I strongly recommend to use it in combination with BufferedReader.

BufferedReader wraps a FileReader and creates a buffer and reads a larger block of block of data.

It’s really faster.

Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

Example:

Note that you should close a reader or create it in the try-with-resources block.

It’s an efficient way to read file line by line in Java and a good choice for reading large files.

Files.readAllLines() and Files.lines() in Java 8

Java 8 provides a new File API for reading lines from a file.

Files.readAllLines() reads all lines from the file.

Example:

The second argument is optional (by default it’s UTF-8), it’s used to decode input stream.

Files.lines() is an API to read file line by line.

I would recommend to use it for reading large files as well.

Example:

Keep in mind that Stream<String>  should be closed.

Scanner

The Scanner is a text scanner that can parse primitive types and string using regular expressions.

You can set a File, Path, Readable or InputStream through the constructor.

And use iterable-like style to read lines from a text file.

Example Scanner with BufferedReader:

Or more or less the same Scanner example with a File:

I recommend using Scanner + BufferedReader approach for reading big text files.

And question or suggestions? Leave a comment.

1 Star2 Stars3 Stars4 Stars5 Stars
Loading...
Scroll Up