Tuesday 11 December 2012

Basics - reading a file

I quite often see new developers struggling with the basics in Java. I guess everyone has to begin somewhere, so here's the first in a series of posts demonstrating some of the basics the you might need when you're starting out.

This post deals with reading a text file line by line. First of all, lets create a text file called names.txt;

Bob
Fred
Jim

Now were going to write a class to read the file. This revolves around the BufferedReader class.

package querky.blog.basics;

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

public class ReadAFile {

  public static void main(String[] args) {
 
    String fileName = "names.txt";
    BufferedReader reader = null;
 
    try {
      System.out.println("Reading " + fileName);
      reader = new BufferedReader(new FileReader(fileName));
      String line = null;
      while ((line = reader.readLine()) != null) {
        System.out.println(line);
      }
    } catch (IOException ioe) {
      ioe.printStackTrace();
    } finally {
      if (reader != null) {
        System.out.println("Closing " + fileName);
        try {
          reader.close();
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }
    }
  }
}

You can see that we create a BufferedReader and then call it's readLine() method in a loop until it returns null. This gives us each line in the file in turn. Notice that we also close the reader in a finally block. This is important as we want to release the resources used.

When run, the program should output this;

Reading names.txt
Bob
Fred
Jim
Closing names.txt

Common problems

The only problem you're likely to encounter is a FileNotFoundException - that is, your program can't find the input file it is supposed to be reading. The error will look something like this;

Reading names.txt
java.io.FileNotFoundException: names.txt (The system cannot find the file specified)
   at java.io.FileInputStream.open(Native Method)
   at java.io.FileInputStream.<init>(FileInputStream.java:106)
   at java.io.FileInputStream.<init>(FileInputStream.java:66)
   at java.io.FileReader.<init>(FileReader.java:41)
   at querky.blog.basics.ReadAFile.main(ReadAFile.java:16)

First, check you have a names.txt file in the right location. What's the right location? As the file name is specified as simply;

String fileName = "names.txt";

Then our program will look for the file in the current working directory, that is to say the directory where the program was launched from. If you don't know what that is, then you can easily find out with a debugging statement;

System.out.println(new File(fileName).getCanonicalPath());

Here we're using the getCanonicalPath() method to show exactly where on the file system Java is looking. If you're getting a FileNotFoundException odds are that the file isn't there or Java doesn't have permission to read it.

No comments:

Post a Comment