Menu
Topics Index
...
`

RandomAccessFile Demo - Java Example Program


RandomAccessFile Demo
class RandomAccessFileDemo
{
    public static void main(String[] args) throws IOException
    {
        File f = new File("E:/FilesFolder/sample.txt");
        RandomAccessFile ras = new RandomAccessFile(f, "rw"); // LINE A
        ras.writeBytes("Merit Campus Your Online Java School.");
        ras.seek(0);//
        
        String[] words = ras.readLine().split(" ");
        
        for(String s : words)
            System.out.print(s + " ");
    
        ras.close();
    }
}
OUTPUT

Merit Campus Your Online Java School.

DESCRIPTION

In the above program at LINE A we have created a RandomAccessFile Object in read/write mode. At LINE B we performed write operation on file by using writeBytes(String s) method. Now the pointer is at the end of the file in order to perform read operation we set the pointer to the starting of the file by seek() method. At LINE C we performed read operation by using readLine(String s). At LINE D we are closing the stream.

© meritcampus 2019

All Rights Reserved.

Open In App