/home/wpollock1/public_html/AJava/RandomAccessDemo.java
// A demo for reading and writing random access files. Here
// all the "production quality" features are omitted, to highlight the
// reading and writing code only.
// The file RandomAccess.dat should be in the same directory as the program.
// It is a text (ASCII) file with each record using 30 bytes (including the
// \r\n ending each line). The first field is the name (20 bytes) and the
// second is the phone number (8 bytes).
//
// Written 4/2010 by Wayne Pollock, Tampa Florida USA
//
import java.io.*;
public class RandomAccessDemo
{
private static final int RECORD_SIZE = 30;
public static void main ( String [] args ) throws Exception
{
RandomAccessFile raf = new RandomAccessFile("RandomAccess.dat", "rw");
// Read the second record (which has index of 1):
raf.seek( 1 * RECORD_SIZE );
String record = raf.readLine();
System.out.println( record );
// Add a new record at the end:
record = String.format("%-19s %8s%n", "Jojo, Mojo", "555-3333");
raf.seek( raf.length() );
raf.writeBytes( record ); // Writes the low byte only, fine for ASCII.
raf.close();
}
}