4

From aperformance optimization point of view: Reading a file in Java - is a buffered reader or scanner better?

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;


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

and the other approach of scanner is..

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
Franz Kafka
  • 10,623
  • 20
  • 93
  • 149
Crazy4Java
  • 269
  • 2
  • 6
  • 13
  • 1
    Remove a call to `println`, give it a file of 10+ megabytes, and see for yourself. – Sergey Kalinichenko Aug 15 '12 at 09:19
  • @dasblinkenlight please expalin in detail ..!! – Crazy4Java Aug 15 '12 at 09:27
  • You have your benchmark code written already, all you need to do is compare the time it takes to go through a large file (say, 10 GB) with both methods. I doubt that you would see a clear winner in this case, although I would go with a `BufferedReader` anyway. – Sergey Kalinichenko Aug 15 '12 at 09:31
  • @user1583868: Put `long ti = System.currentTimeMillis();` at the start and `System.out.println("Time elapsed: " + (System.currentTimeMillis() - ti));` at the end of each version of the program and then run each with a large `sample.txt` and check which is faster... – beny23 Aug 15 '12 at 09:33

1 Answers1

6

BufferedReader is a lot faster than Scanner because it buffers the character so you don't have to access the file each time you want to read a char from it.

Scanner are of particular use such as reading primitive data type directly and is also used for regular expressions.

I have used Scanner and BufferedReader both and BufferedReader gives significant fast performance. You can test it yourself too.

dejavu
  • 3,236
  • 7
  • 35
  • 60
  • 4
    In jdk6 some version (do not remember which) Scanner has also a buffer of 1 KB, which is more then enough. – Eugene Aug 15 '12 at 09:33