How to write to a Random Access File

The WriteRAF example writes ten records to a random access file RAFile1.dat. Obviously, in practice, we would use a random access for files of at least several thousand records. Each record consists of a string corresponding to a person's address. Random
access records can consist of fields corresponding to any of the Java primitive data types.

WriteRAF

import java.io.*;

public class WriteRAF
{
public static void main(String[] args) throws IOException
{
int i;
String text;
RandomAccessFile fileOut;

fileOut = new RandomAccessFile(''RAFile1.dat", "rw");
for (i=1; i<11; i++)
{
text = "Address of " + i + " person\n";
System.out.println("offset: " + fileOut.length()
);
fileOut.seek(fileOut.length() );
fileOut.writeChars(text);
}
fileOut.close();
}
}



In line 11, we create a random access file object, fileOut, which corresponds to physical file RAFile1.dat using the RandomAccessFile constructor. When creating a random access file, we need to specify whether the file is for reading and writing, "rw", or for reading only, "r".

We execute a for loop (lines 12–17) that writes each record to the file. In line 15, we position the file pointer at the end of the file so that we append the records to the file in the right order. The java.io.RandomAccessFile.length method returns the length, in bytes, of the file. We then use this length as the offset argument in the java.io.RandomAccess.seek method. Because each string is 20 characters, or 40 bytes, in length, we know the offsets for each record will be 0, 40, 80, 120, and so on. The println statement in line 14 simply confirms this.

In line 16, we use RandomAccessFile.writeChars to write the address string, text, as a sequence of characters to the file.

No comments:

Post a Comment