Friday, August 6, 2021

How to read file line by line in Java - BufferedReader Scanner Example Tutorial

Line by Line reading in Java using BufferedReader and Scanner
There are multiple ways to read files line by line in Java. A most simple example of reading file line by line is using BufferedReader which provides the method readLine() for reading files. Apart from generics, enum and varargs Java 1.5  has also introduced several new classes in Java API one of the utility classes is Scanner, which can also be used to read any file line by line in Java. Though BufferedReader is available in Java from JDK 1.1,  java.util.Scanner provides more utility methods compared to BufferedReader. Scanner has method like hasNextLine() and nextLine() to facilitate line by line reading of file's contents.

The nextLine() returns String similar to readLine() but the scanner has more utility methods like nextInt(), nextLong() which can be used to directly read numbers from a file instead of converting String to Integer or other Number classes.

By the way, a Scanner is rather a new approach for reading a file, and BufferedReader is the standard one. This is my 6th tutorial on Java IO,  In the last couple of post, we have seen creating file and directory in Java, parsing XML files using DOM and how to read properties file in Java. In this post, we will focus on reading the file line by line in Java using both BufferedReader and Scanner.

Reading file line by line in Java - BufferedReader Example

Java file read line by line example BufferedReader ScannerIn this example, we are using BufferedReader for reading file content line by line. BufferedReader needs an InputStream which is a FileInputStream in this case and readLine() returns a value of line or null if the end of Stream has reached. The line is terminated with line terminator e.g. \n or \r



import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * BufferedReader and Scanner can be used to read line by line from any File or
 * console in Java.
 * This Java program demonstrate line by line reading using BufferedReader in Java
 *
 * @author Javin Paul
 */

public class BufferedReaderExample {  

    public static void main(String args[]) {
     
        //reading file line by line in Java using BufferedReader      
        FileInputStream fis = null;
        BufferedReader reader = null;
     
        try {
            fis = new FileInputStream("C:/sample.txt");
            reader = new BufferedReader(new InputStreamReader(fis));
         
            System.out.println("Reading File line by line using BufferedReader");
         
            String line = reader.readLine();
            while(line != null){
                System.out.println(line);
                line = reader.readLine();
            }          
         
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
         
        } finally {
            try {
                reader.close();
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
  }

Output:
Reading File line by line using BufferedReader
first line in file
second line
third line
fourth line
fifth line
last line in file


while using FileInputStream or any IO Reader don't forget to close the stream in finally block so that file descriptor associated with this operation get released. If not closed properly Java program may leak file descriptors which is a limited resource and in worst case program will not be able to open any new file. If you are Java 7 then you can use Automatic resource management or ARM blocks to let those resource automatically get closed by Java.


Reading file line by line in Java - Scanner Example

Scanner is new addition in Java 1.5 along with several other changes like auto-boxing and has been a preferred choice for reading inputs from the console. Since Scanner is able to read from InputStream , it can also be used to read from text File and it provide many utility methods to read line by line contents using nextLine() or nextInt() etc.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * @author Javin Paul
 * Java program to read file line by line using Scanner. Scanner is a rather new
 * utility class in Java and introduced in JDK 1.5 and preferred way to read input
 * from console.
 */

public class ScannerExample {
 

    public static void main(String args[]) throws FileNotFoundException  {
     
       //Scanner Example - read file line by line in Java using Scanner
        FileInputStream fis = new FileInputStream("C:/sample.txt");
        Scanner scanner = new Scanner(fis);
     
        //reading file line by line using Scanner in Java
        System.out.println("Reading file line by line in Java using Scanner");
     
        while(scanner.hasNextLine()){
            System.out.println(scanner.nextLine());
        }
     
        scanner.close();
    }  
     
}

Output:
Reading file line by line in Java using Scanner
first line in file
second line
third line
fourth line
fifth line
last line in file


That's all on How to read files line by line in Java. We have seen two simple examples of line-by-line reading using BufferedReader and Scanner. If you look code with Scanner looks cleaner and give a wide variety of data conversion method it supports, it just a handy choice for reading file line by line in Java.


Other Java IO tutorials from the Javarevisited blog

7 comments :

Javin @Linkded List vs ArrayList said...

Thanks Sanaulla for JDK 7 way of reading all lines from File, I know there are lot of useful File API changes in Java7 which is worth looking, thanks for bringing this up.

Anonymous said...

How to remove duplicate lines from file?

manju said...

Scanner should be used when file size is small and if u r reading character based input.
Its highly advised not to use it for large files as it does utf-8 conversion and is very slow.

Bart said...

Everything works perfectly. but! Line is null ;(

javin paul said...

@Bartomeij, can you please post some lines from the file you are reading? its worth check if first line is empty or not. if you can read the file without any error then there is no reason that line would be empty until file itself contain empty lines.

Unknown said...

Is there are way to check the number of lines from the scanner prior to "scanner.hasNextLine" to prevent getting stuck in an infinited while loop?

Anonymous said...

All the examples EVERYWHERE regarding scanner DOONT show use how to read a SPECIFIC line in a file; E.g. starting from line 2, or perhaps line 12 to extract whate ever data in a file you know is there!

Post a Comment