How to use random access file


 

How to use random access file

In this section, you will learn the use of RandomAccessFile class.

In this section, you will learn the use of RandomAccessFile class.

How to use random access file

In this section, you will learn the use of RandomAccessFile class.

RandomAccessFile allows read and write operations to any specified location in a file. Here data can be read from or written to in a random manner. Unlike other  input and output streams, RandomAccessFile is used for both reading and writing files. A random access file treats with a large array of bytes and uses the file pointer  to deal with the index of that array. This file pointer points the positions in the file where the reading or writing operation has to be done.  It defines operation modes (read / write). 

r mode- Open for reading only.

rw mode- Open for reading and writing.

seek(file.length()) method- It jumps the file pointer at the specified location.  Here, file.length( ) returns the end of the file.

rand.close() method- It closes the random access file stream.

writeBytes( ) method- It simply writes the content into the file. 

readByte() method- It reads a single byte from the file.

readLine() method- It reads the line from the file.

If you want to perform read operation with RandomAccessFile, then you have to create an instance with 'r' mode:

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

and if you want to perform write operation with RandomAccessFile, then you have to create an instance with 'rw' mode:

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

Here we have created two examples performing read and write operations respectively.

Example performs read operation:

import java.io.*;

public class UseOfRandomAccessFile {
  public static void main(String[] argsthrows Exception {
    File file = new File("c:/new.txt");
    RandomAccessFile access = new RandomAccessFile(file, "r");
    byte b = access.readByte();
    System.out.println("Read first character of file: " (charb);
    System.out.println("Read full line: " + access.readLine());
    access.close();
  }
}

Example performs write operation:

import java.io.*;

public class UseOfRandomAccessFile {
  public static void main(String[] argsthrows Exception {
    File file = new File("c:/new.txt");
    RandomAccessFile access = new RandomAccessFile(file, "rw");
    System.out
        .println("Read first character of file: " + access.readLine());
    access.seek(file.length());
    access.writeBytes("Truth is more important than facts");
    access.close();
  }
}

Ads