The ReadRAF example reads the random access file, RAFile1.dat, created in the previous section. We retrieve the record identified by an offset of 80 bytes, the third record,
and print its contents to the standard output stream.
ReadRAF
import java.io.*;
public class ReadRAF
{
public static void main(String[] args) throws
IOException
{
char singlechar;
StringBuffer address;
RandomAccessFile fileIn;
fileIn = new RandomAccessFile(''RAFile1.dat", "r");
fileIn.seek(80);
address = new StringBuffer(20);
while ((singlechar = fileIn.readChar()) != '\n')
{
address.append(singlechar);
}
System.out.println(address);
fileIn.close();
}
}
In line 11, we use the RandomAccessFile constructor to create our file object, fileIn, only this time we specify a read-only file. If we attempt to write to this file with any of the write methods, an IOException will be thrown.
In line 12, we position the file pointer at an offset of 80 bytes using the java.io.Random-AccessFile.seek method.
In lines 14–16, we have a while loop that reads each single character from the file and appends to a StringBuffer variable, address. The while loop is terminated when we read the line separator. The single characters are read from the file using the java.io.RandomAccess-File.readChar method. The record contents, which are now held in the address variable, are printed to the standard output stream in line 17.
How to Read from a Random Access File
Tags
# Input/Output
# Reading from a Random Access File
Share This
Reading from a Random Access File
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment