Menu
Topics Index
...
`

Random Access File Demo - Java Example Program


Random Access File Demo
import java.io.*;

class RandomAccessFileDemo
{
    public static void main(String arg[])
    {
        try
        {
            String input = "Learn Java With Merit Campus";
            System.out.println("Input : " + input);
            RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");
            raf.writeBytes(input);
        
            // MOVE TO 6TH POSITION AND READ FOUR CHARACTERS
            raf.seek(6);
            String s = "" + (char) raf.read() + (char) raf.read() + (char) raf.read() + (char) raf.read();
            System.out.println("String read is : " + s);
        
            // CHANGE 'With' TO 'From'
            raf.seek(11);
            raf.writeBytes("From");
            raf.seek(0);
            System.out.println("After changing : " + raf.readLine());
        
            // TRUNCATE TO 10 CHARACTERS
            raf.setLength(10);
            raf.seek(0);
            System.out.println("After truncating : " + raf.readLine());
        
            raf.close();
        }
        catch(IOException ioex)
        {
            System.out.println("Read write failed - " + ioex.getMessage());
        }    
    }
}
OUTPUT

Input : Learn Java With Merit Campus
String read is : Java
After changing : Learn Java From Merit Campus
After truncating : Learn Java

DESCRIPTION

We created a RandomAccessFile and have written the content Learn Java With Merit Campus into that file. Firstly we moved to the letter 'J' by using seek(6) and then read the next four characters, which are nothing but "Java". Later we moved to the letter 'W' using seek(11) and have written the bytes from the string "From". Finally we set the length to 10, which caused the file to be truncated to 10 characters and so it became just "Learn Java".

© meritcampus 2019

All Rights Reserved.

Open In App