|  
               
                The streams discussed in Chapter 
                  9: Java dealt with data going in one direction (in or out) 
                  and with data read or written sequentially. A common requirement, 
                  however, is to access a file in a way that lets you both read 
                  and write to it and also to move to any point within the file 
                  to carry out those operations. The RandomAccessFile 
                  class allows just for this type of access to any random 
                  place with in the file.   The RandomAccessFile object provides 
                  a file pointer that acts as a index to indicate where 
                  in the file a read or write operation begins. In that sense, 
                  a RandomAccessFile object acts like 
                  an array representing the bytes of the file. One difference 
                  is that a write operation that goes past the end of the array 
                  will append the data as if the array had been automatically 
                  extended. Attempts to read past the end of the file will, however, 
                  for many of the read methods result in an EOFException. 
                 The class has two constructors, one of which uses a File 
              object to specify the file and the other a string name for the file. 
              A second argument determines the access mode for the file. A random 
              access file object can be created just for reading as follows:  
              RandomAccessFile file_readonly = new RandomAccessFile 
                ("data.txt", "r"); A file for both reading and writing could be created like this:  
              File my_file = getMyFile();RandomAccessFile file_readonly = new RandomAccessFile (my_file, 
                "rw");
 If the file does not exist, the readonly mode would result in a 
              IOException. For the read-write mode, the file will be created if 
              it does not exist. See the class specifications of RandomAccessFile 
              for a long list of available read and write methods. (The class 
              implements the DataInput and DataOutput 
              interfaces just like DataInputStream and 
              DataOutputStream, resp.) There is also 
              the method  
              void seek (long pos)  that allows you to specify the index for where read and write operations 
              will start. The method  
              long getFilePointer () which returns the current position of the pointer. And the method 
              int skipBytes (int n) jumps the pointer by n bytes from its current location. Demo of RandomAccessFile The following simple demo program illustrates the basics of working 
              with the RandomAccessFile. From the command 
              line you specify where in a file of integer numbers where you want 
              a number to be written. 
              
                 
                  | RandomFileTest.java |   
                  |  
                       import java.io.*;
 /**
 * Use RandomAccessFile to write a number into 
                        a file.
 * Command line specifies the single integer 
                        value to
 * write, the position in the file where it 
                        is to be
 * written, and the name of the file, which 
                        should contain
 * a series of integer values. The position 
                        will be in
 * terms of integer values, not bytes. The 
                        file will be
 * created if it doesn't exist already.
 **/
 public class RandomFileTest  {
 
 
 public static void main (String [] args) {
 
 int value = 0;
 long position = 0;
 
 if (args.length < 3) {
 System.out.println 
                        ("Usage: java RandomFileTest value position filename");
 System.exit(0);
 }
 
 try {
 value = Integer.parseInt 
                        (args[0]);
 }
 catch (NumberFormatException nfe) 
                        {
 System.out.println 
                        ("Bad number value!");
 System.out.println 
                        ("Usage: java RandomFileTest value position filename");
 System.exit (0);
 }
 
 // Check
 try {
 position = Long.parseLong 
                        (args[1]);
 // Treat number as 
                        absolute value.
 if (position < 0) 
                        position = -position;
 position = 4*position; 
                        // 4 bytes per integer.
 }
 catch (NumberFormatException nfe) 
                        {
 System.out.println 
                        ("Bad position value!");
 System.out.println 
                        ("Usage: java RandomFileTest value position filename");
 System.exit (0);
 }
 
 RandomAccessFile file = null;
 try {
 file = new RandomAccessFile 
                        (args[2], "rw");
 }
 catch (FileNotFoundException ffe) 
                        {
 System.out.println("File 
                        not found. Will create it.");
 }
 
 try {
 
 // Append if position 
                        beyond the end of the file.
 if (position > 0 && 
                        position >= file.length ()) {
 position 
                        = file.length ();
 }
 
 // Move to the desired 
                        position and write the number.
 file.seek (position);
 file.writeInt (value);
 
 // Move back to the 
                        start of the file and print it out
 file.seek (0);
 int num_entries = 
                        (int)(file.length () / 4);
 for (int i=0; i < 
                        num_entries; i++) {
 System.out.printf 
                        ("%10d", file.readInt ());
 if (i 
                        != 0 && (i%6) == 0) System.out.println();
 }
 System.out.println();
 
 }
 catch (IOException ioe) {
 System.out.println 
                        ("IO Exception = " + ioe);
 }
 } // main
 
 } // RandomFileTest
 |    References & Web 
              Resources Most recent update: August 19, 2005 |