How to use RandomAccessFile class in Java?

Below code shows how to use RandomAccessFile java class –

/****************************************************************************************
 * Created on 08-2011 Copyright(c) https://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.java.io;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Created by Vigilance India.
 * User: https://kodehelp.com
 * Date: Aug 1, 2011
 */
public class RandomAccessFileExample {
     public static void main(String[] args) {
        try {
            /*Create a new instance of RandomAccessFile class. We'll do a "r"
            read and "w" write operation to the file. If you want to do a write
            operation you must also allow read opeartion to the RandomAccessFile
            instance.*/
            
            RandomAccessFile raf = new RandomAccessFile("Fruits.dat", "rw");

            
           /* Let's write some text to the end of the file*/
            
            String fruits[] = new String[5];
            fruits[0] = "Apple";
            fruits[1] = "Orange";
            fruits[2] = "Grapes";
            fruits[3] = "Banana";
            fruits[4] = "Strawberry";

            for (int i = 0; i < fruits.length; i++) {
                raf.writeUTF(fruits[i]);
            }

            //
            // Write another data at the end of the file.
            //
            raf.seek(raf.length());
            raf.writeUTF("Blackberry");

            //
            // Move the file pointer to the beginning of the file
            //
            raf.seek(0);

            //
            // While the file pointer is less than the file length, read the
            // next strings of data file from the current position of the
            // file pointer.
            //
            while (raf.getFilePointer() < raf.length()) {
                System.out.println(raf.readUTF());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.