Support Forums

Full Version: Teaching Random Access Files!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This concept of I/O using Random Access File is relatively new to a lot of people and im not sure as to why, so I thought my next tutorial will be on Random Access Files (RAF).

As you may or may not know, the usual way we go about I/O streams such as reading/writting data is sequential. It reads/writes one at a time, which is inefficient when trying to locate certain data quickly. Also, they do not provide a means of updating data without copying the entire files contents and updating. This can all be optimized using RAF.

The RandomAccessFile class can be found here,
http://java.sun.com/j2se/1.4.2/docs/api/...sFile.html

Here is a quick example of a program that first writes to a specified txt file using a FileOutputStream wrapped by a DataOutputStream. After a successful write, we use RAF to read and write to the txt file. Some parts of this snippet may confuse some, but dont be afraid to ask.
Code:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;

public class lol {

    public static void main(String args[]) {
            File f = new File("C:/Users/Anthony Calandra/Desktop/lol.txt");
            try { // Format the above file with 100 integers
                DataOutputStream dataOut = new DataOutputStream(new FileOutputStream(f));
                for (int i = 0; i < 100; i++)
                    dataOut.writeInt(49); // write the number: 1 using ASCII code(#49)
                dataOut.close();
                System.out.println("Successfully wrote 100 integers to the file.");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("- Exception caught -");
            }

            try { // Apply reading/writting using RAF
                RandomAccessFile raf = new RandomAccessFile(f, "rw"); // rw = read/write
                int offset = 10; // starting index for writing
                byte[] readBytes = new byte[(int)raf.length()];
                if (offset < raf.length()) {
                    raf.seek(offset);
                    System.out.println("Current value: " + raf.readInt());
                    raf.seek(offset);
                    System.out.print("Writting new value according to offset \n");
                    raf.writeInt(50); // write the number: 2 using ASCII code(#50)
                } else
                    System.out.println("Invalid offset!");
                
                System.out.println(raf.readLine());
                raf.close();
                System.out.println("Operation complete!");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("- Second Exception caught -");
            }
    }
}

Thanks for reading.