The RandomAccessFile seems to scare off Java beginners, which is too bad because it is by far the easiest tool for reading a file. Java beginners are almost always introduced to streams and very often proceed to read a file using stream I/O. This is the hard way.
Streams should be used where you have real streams. Getting a file from disk into memory shouldn't involve streams except in the rare case where the file is simply too big to be read all at once. File's under ten megabytes are easily written and read in a single step if they are opened as RandomAccessFile files.
Let's look at the code to have the computer read the HTML file you are now reading. Begin by opening the file for read ("r") access.
RandomAccessFile raf = new RandomAccessFile
( "C:/MRWebsite/Articles/RAF.html", "r" );
That code declares a RandomAccessFile variable and then opens a specific file for read access. It's about the same as opening the file as a stream, but from here on it gets easier. Next, you'll need a byte array that's the same size as the file. Since the size of the file is raf.length(), this is all you need:
byte[] bytes = null;
. . .
bytes = new byte[ (int) raf.length() ];
Now you've got a place in memory to put the contents of the file. All that remains is to actually read the file into that byte array:
raf.read( bytes );
raf.close(); // optional
You could use the readFully() method but it is the same as read() when the file is just opened and the byte array is as long as the file. If you are done with the file, you should close it.
That's all there is! You now have the same bits in the byte array that are in the disk file. Process them as your application requires. The following program shows these steps in a completed program that reads the contents of the HTML you are now reading and dumps them to the Java console.
import java.io.*;
public class RAFsample{
public static void main( String[] args ) {
byte[] bytes = null;
try {
RandomAccessFile raf = new RandomAccessFile
( "C:/MRWebsite/Articles/RAF.html", "r" );
bytes = new byte[ (int) raf.length() ];
raf.read( bytes );
raf.close();
}
catch( IOException e ) {
System.err.println( e );
System.exit( 1 );
}
System.out.println( new String(bytes) );
System.exit( 0 );
}
} // end of class RAFsample
© 2005 by Martin Rinehart
Back to Articles