Yikes -- sorry folks, this article is pretty old.
Much newer tips and articles related to reading files with Java are located here:
Introduction
While Java used to be thought of only as a language for developing applets, it has recently been promoted more as a great general-purpose programming language, and as a great language for developing servlets (Java code that runs on a web server).
A common requirement of (a) general-purpose coding and (b) servlet coding is the need to read and write text data files. In this article we'll look at the techniques used to open and read text data files using the methods available in Java JDK 1.0.x. In a future article, we'll focus on the best ways to open and read data files using the methods available in JDK 1.1.x and higher.
Opening a text data file using Java JDK 1.0.x
When reading data files with Java, you'll deal with the data file as an input stream of information. Using JDK 1.0.x, you'll typically open a file for read access with the FileInputStream class. There are a few different ways to do this, but I'll show you the method I use most often.
Opening a file for read access with Java JDK 1.0.x can take as many as four steps, although these aren't all required (more on this shortly). The four steps I normally follow are this:
- Open the file with the File class;
- Create a FileInputStream object using the File object;
- Convert the FileInputStream to a BufferedInputStream to greatly increase file reading speed;
- Convert the BufferedInputStream to a DataInputStream; the methods of DataInputStream give me a fair amount of flexibility in reading the data.
Okay, that's the four steps I normally take. Listing 1 shows what this looks like in Java code.
File f = new File("mydata.txt"); FileInputStream fis = new FileInputStream(f); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis); |
Listing 1: | These are the four steps I normally take to open a file for read access using Java JDK 1.0.x. |
This code can actually be condensed if you just give the FileInputStream constructor the name of a file, instead of passing it the File object. This would look like this:
- FileInputStream fis = new FileInputStream("mydata.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
Although this works fine, I normally use the File object anyway, because the File class offers many nice methods for dealing with files in a platform-independent way. For instance, it has methods such as canRead() and canWrite() that help me deal with permissions, exists() helps me test whether the file is really there, and isFile() and isDirectory() help me determine whether an unknown file is a file or directory.
The step of creating the BufferedInputStream object (bis) is not required either, but our own tests have shown that reading a 100K file can take nearly 10 times longer if you don't call the BufferedInputStream object.
Need to use "try/catch"
As a practical matter, the four steps shown above cannot be considered complete by themselves. They must be wrapped in a Java try/catch statement, because the FileInputStream class can throw an IOException if something goes wrong. We'll show you how to include these steps in a try/catch statement in just a few moments.
Reading from the data file
Once you have the data file open, reading from the file is a fairly simple matter - especially if you use the DataInputStream class. This class has many methods for reading data files that greatly simplify the process, including the one's I use most often: readFloat(), readInt(), readLine().
Here's a simple example of how to read a line of information from a data file using the readLine() method, which I probably use most often:
- String record = dis.readLine();
You can use a call like this any time you want to read a line of data from the file as a String object. If you'd like to read the entire data file like this, you can simple put the readLine() statement into a while loop. This technique is shown in Listing 2.
String record = null;
try { while ( (record=dis.readLine()) != null ) { } catch (IOException e) { |
Listing 2: | This listing shows a method that can be used to read every line of information from a data file using the readLine() method inside of a while loop. |
We're almost home now
There are only two things we haven't shown you yet that are still required. The first item is the need to import the java.io package. This is needed so you can access the classes we've discussed so far. The second item we haven't discussed is the need to close the data file in a finally clause of the try/catch statement. We'll show both of these items in our final example.
Putting it all together
Now that we've shown the separate parts of the open and read operations, let's put it all together in a simple example. Listing 3 shows a completely-working example of a technique we often use to open a data file, read it's contents, and close the file when we're finished with it. We implement our technique here in a method named readMyFile.
import java.io.*; class FileReadTest { public static void main (String[] args) { FileReadTest f = new FileReadTest(); f.readMyFile(); } void readMyFile() { DataInputStream dis = null; String record = null; int recCount = 0; try { File f = new File("mydata.txt"); FileInputStream fis = new FileInputStream(f); BufferedInputStream bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); while ( (record=dis.readLine()) != null ) { recCount++; System.out.println(recCount + ": " + record); } } catch (IOException e) { // catch io errors from FileInputStream or readLine() System.out.println("Uh oh, got an IOException error!" + e.getMessage()); } finally { // if the file opened okay, make sure we close it if (dis != null) { try { dis.close(); } catch (IOException ioe) { } } } } } |
Listing 3: | This listing shows a complete working example of a program that (a) opens a data file, (b) reads records of information from the file, and (c) prints each record of information from the file to standard output, placing a line number before each record. |
Final thoughts and source code
Although the example shown in Listing 3 doesn't bring any great new capabilities to the world, it does demonstrate the proper methods for opening and reading data from data files using the classes of Java JDK 1.0.x.
If you'd like to download the code shown in Listing 3, just click here, and the Java code will be displayed in your browser. Then just use the "File | Save As" option of your browser to download the source code to your system.