Tags

,

When writing a Java application, one of the most common tasks to perform is to read an input file, one line at a time. For this purpose, I frequently use a BufferedReader class. But the problem is creation of the class.

While reading input has always being painful in any programming language, Java has tried to make the task ‘simple’. And thus I end of using around 4 class along with the BufferedReader.

Out of frustration, I finally wrote a helper method/class for this purpose. Below is the code for the same. The idea is to use a BufferedReader as a separate class, along with a callback method that will be invoked each time a line is read from the input. This, hopefully will make the task of reading a file easier.

Note: As usual, the code below is released using Apache 2.0 License.

Custom BufferedReader class.

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

public class BufferedReaderWithCallback
{
    BufferedReader mReader;

    public BufferedReaderWithCallback()
    {
        /* empty by design */
    }

    public boolean open(String inputFile)
    {
        try {
            mReader = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(inputFile))), 8000);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    public boolean read(LineCallback callback)
    {
        String str;

        try {
            while ( (str = mReader.readLine()) != null ) {
                callback.process(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    public boolean close()
    {
        try {
            mReader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}

The interface for the callback.

public interface LineCallback
{
    public void process(String data);
}
Advertisements