How to read a plain text file in Java

This tutorial shows several ways for reading plain text files in Java.

The techniques we use here are totally JDK built-in and don’t depend on external libraries.

1- BufferedReader

The most common way for reading plain text files in Java is through using a FileReader wrapped by a BufferedReader. This technique is very efficient for reading large text files.

2- Scanner

Another common way is to wrap FileReader with a Scanner object. This technique is also efficient for reading large text files.

3- Java nio

Using the nio package which is introduced in JDK 7, we can store a whole plain text file into a List<String> using Files.readAllLines(). It is clear that this method is not efficient for reading large text files as it loads the whole file into the memory which can cause memory leaks in case of huge files.

4- Java 8

With Java 8, you can store the contents of a text file to List<String> using one line as the following:

Again, this technique is commonly used for reading small to midrange text files as it loads the whole file contents into the memory.

 

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar