View RSS Feed

My Java Tips

Reading an ASCII file (BufferedReader)

Rate this Entry
by , 11-10-2011 at 05:14 PM (3988 Views)
Normally we give input to Java applications from command prompt or through GUI. But sometimes, when inputs are in bulk, we can use ASCII files for input. Such files must have some agreed upon pattern so Java parser can understand the meaning of the text. There are many ways to read a file but one of the simplest way is to use BufferedReader class which is found in java.io package.


First prompt the user to enter the file name with path. This can be done using:

Java Code:
String fileName = "";
System.out.println("Please enter the file name: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
fileName = br.readLine();
Now we have the file name in a string called fileName. Create a File object and pass the filename to it. This File object will be used later. We will use BufferedReader for reading the text file. BufferedReader is efficient for reading characters through character input stream. Buffer size can be specified but the default size is quite large to accomplish the normal tasks.

BufferedReader has two constructors. One with the buffer size and one without the buffer size. The default buffer size is 8192 characters.

When your BufferedReader object is initialized, you can use its readLine method to read the file line by line. You may parse lines as they are fetched and store only the lines that are required for further processing.

Java Code:
    StringBuffer contents = new StringBuffer();
    BufferedReader input = null;
    try {
      input = new BufferedReader( new FileReader(aFile),1 );
      String line = null; //not declared within while loop
      while (( line = input.readLine()) != null){
        contents.append(line);
        contents.append(System.getProperty("line.separator"));
      }
    }
    catch (FileNotFoundException ex) {
      ex.printStackTrace();
    }
    catch (IOException ex){
      ex.printStackTrace();
    }
Reading the file may raise following exceptions:
FileNotFoundException
IOException

It is always a good idea to write separate catch blocks for known exceptions.

Submit "Reading an ASCII file (BufferedReader)" to Facebook Submit "Reading an ASCII file (BufferedReader)" to Digg Submit "Reading an ASCII file (BufferedReader)" to del.icio.us Submit "Reading an ASCII file (BufferedReader)" to StumbleUpon Submit "Reading an ASCII file (BufferedReader)" to Google

Categories
Java SE

Comments