Read text file in Java

There are many ways to read a text file in Java. The sample I created here is one of the easy and quick way. I used BufferedReader with a FileReader object. The BufferedReader implements Closable interface, and hope we all are using Java 7 or above, so we can leverage the try-with-resource to automatically close it once our job done.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReadSample {

    public static void main(String [] argv) throws IOException {

        try (BufferedReader bufferedReader =
                new BufferedReader(new FileReader("test.txt"))) {
            
            String line;
            while ((line = bufferedReader.readLine()) != null){
                System.out.println(line);
            }
        }
    }
}
Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus