CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Files

Text and Binary Files
Random-access files
Read and write

Two interfaces implemented by the RandomAccessFile class

DataOutput
DataInput

Methods of the RandomAccessFile class used for input and output

Method Throws Description
seek(long) IOException Sets the pointer to the specified number of bytes from the beginning of the file. If set beyond the end of the file, the pointer will be moved to the end of the file.
length() IOException Returns a long for the number of bytes in the file.
setLength(long) IOException Sets the length of the file to the specified number of bytes.
long getFilePointer() IOExceptionReturns the current offset, in bytes, from the beginning of the file to where the next read or write occurs.
final void writeChar(int v) IOException Writes a character to the file as a two-byte Unicode, with the high byte written first.
final void writeChars(String s)IOException Writes a string to the file as a sequence of characters.
close() IOException Closes the file.

Code that writes data to a file

RandomAccessFile productsFile =
    new RandomAccessFile(file, "rw");

// write 3 records with codes and prices to the file
String[] codes = {"java", "jsps", "txtp"};
double[] prices = {49.5, 49.5, 20.0};
for (int i = 0; i < codes.length; i++)
{
    productsFile.writeChars(codes[i]);
    productsFile.writeDouble(prices[i]);
}

productsFile.close();

Code that reads data from a file

final int RECORD_LENGTH = 16;  // 4 chars @ 2 bytes per char
                               // + 1 double @ 8 bytes

RandomAccessFile productsFile =
    new RandomAccessFile(file, "r");

// move the pointer to the third record
int recordNumber = 3;
productsFile.seek((recordNumber - 1) * RECORD_LENGTH);

// read the third record
String code = "";
for (int i = 0; i < 4; i++)
    code += productsFile.readChar();
double price = productsFile.readDouble();

productsFile.close();
Previous | Introduction | Connect | Read and write | Fixed-length strings | Test random access | Class with a random-access file | Address book