RandomAccessDemo.java

Download RandomAccessDemo.java

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