Home Tutorial Java Core Files How to use random access file

 
 

Share on Google+Share on Google+
How to use random access file
Posted on: April 3, 2006 at 12:00 AM
Advertisement
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();
  }
}
Advertisement

Related Tags for How to use random access file:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 3, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com