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.

 1import java.io.BufferedReader;
 2import java.io.FileReader;
 3import java.io.IOException;
 4
 5public class FileReadSample {
 6
 7    public static void main(String [] argv) throws IOException {
 8
 9        try (BufferedReader bufferedReader =
10                new BufferedReader(new FileReader("test.txt"))) {
11            
12            String line;
13            while ((line = bufferedReader.readLine()) != null){
14                System.out.println(line);
15            }
16        }
17    }
18}
comments powered by Disqus