Thursday 21 June 2012

Read file line by line in Java

We can use java.io.BufferedReader class for efficiently reading a text file line by line.

public class BufferedReader
extends Reader
The java.io.BufferedReader class is a subclass of java.io.Reader that is chained to another Reader class to buffer input.This allows more efficient reading of characters and lines.The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

There are two constructors. One has a default buffer size (8192 characters); the other requires the programmer to specify the buffer size:

public BufferedReader(Reader in, int buffer_size)
public BufferedReader(Reader in)

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

 BufferedReader in = new BufferedReader(new FileReader("t1.txt"));
 
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

BufferedReader is notable for its readLine() method that allows you to read text a line at a time.


Read File Line by Line using BufferedReader and FileReader


The following code shows how to read a text file line by line using FileReader and BufferedReader.

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

public class ReadFileLineByLine {

    /**
     * @param Pass
     *            Filename as command-line argument
     * @throws IOException
     **/
    public static void main(String[] args) {
        BufferedReader br = null;
        String cline;
        try {
            br = new BufferedReader(new FileReader(args[0]));

            while ((cline = br.readLine()) != null) {
                System.out.println(cline);
            }

        } catch (IOException e) {
            System.out.println(e);
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


One drawback of the above code is that FileReader and FileWriter, which implicitly use the system's default character encoding.In some scenarios this default is not appropriate(for example, read an XML file with specified encoding).Here you can make use of java.io.InputStreamReader class.

public class InputStreamReader
extends Reader
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

 The following code shows how to read a text file line by line, using an explicit encoding.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadFileLineByLine {

    /**
     * @param Pass
     *            Filename as command-line argument
     * @throws IOException
     **/
    public static void main(String[] args) {

        BufferedReader br = null;
        String cline;
        try {
            FileInputStream fin = new FileInputStream(args[0]);

            br = new BufferedReader(new InputStreamReader(fin, "UTF-8"));

            while ((cline = br.readLine()) != null) {
                System.out.println(cline);
            }

        } catch (IOException e) {
            System.out.println(e);
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


If you remove reference to encoding from InputStreamReader class, it will still work -- the system's default encoding will simply be used instead.

1 comment:

  1. Thank you. Btw. since Java 7 you can use try-with-resources, which simplifies closing files.

    ReplyDelete