Tutorial

Java RandomAccessFile Example

Published on August 3, 2022
Default avatar

By Pankaj

Java RandomAccessFile Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java RandomAccessFile provides the facility to read and write data to a file. RandomAccessFile works with file as large array of bytes stored in the file system and a cursor using which we can move the file pointer position.

Java RandomAccessFile

Java RandomAccessFile, RandomAccessFile in java, Java RandomAccessFile read write append example RandomAccessFile class is part of Java IO. While creating the instance of RandomAccessFile in java, we need to provide the mode to open the file. For example, to open the file for read only mode we have to use “r” and for read-write operations we have to use “rw”. Using file pointer, we can read or write data from random access file at any position. To get the current file pointer, you can call getFilePointer() method and to set the file pointer index, you can call seek(int i) method. If we write data at any index where data is already present, it will override it.

Java RandomAccessFile read example

We can read byte array from a file using RandomAccessFile in java. Below is the pseudo code to read file using RandomAccessFile.

RandomAccessFile raf = new RandomAccessFile("file.txt", "r");
raf.seek(1);
byte[] bytes = new byte[5];
raf.read(bytes);
raf.close();
System.out.println(new String(bytes));

In the first line, we are creating RandomAccessFile instance for the file in read-only mode. Then in the second line, we are moving the file pointer to index 1. We have created a byte array of length 5, so when we are calling read(bytes) method, then 5 bytes are read from file to the byte array. Finally, we are closing the RandomAccessFile resource and printing the byte array to console.

Java RandomAccessFile write example

Here is a simple example showing how to write data to a file using RandomAccessFile in java.

RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek(5);
raf.write("Data".getBytes());
raf.close();

Since RandomAccessFile treats the file as a byte array, write operation can override the data as well as it can append to a file. It all depends on the file pointer position. If the pointer is moved beyond the file length and then write operation is called, then there will be junk data written in the file. So you should take care of this while using write operation.

RandomAccessFile append example

All we need is to make sure file pointer is at the end of the file to append to a file. Below is the code for append to file using RandomAccessFile.

RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek(raf.length());
raf.write("Data".getBytes());
raf.close();

Java RandomAccessFile Example

Here is a complete java RandomAccessFile example with different read and write operations.

package com.journaldev.files;

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

public class RandomAccessFileExample {

	public static void main(String[] args) {
		try {
			// file content is "ABCDEFGH"
			String filePath = "/Users/pankaj/Downloads/source.txt"; 
			
			System.out.println(new String(readCharsFromFile(filePath, 1, 5)));

			writeData(filePath, "Data", 5);
			//now file content is "ABCDEData"
			
			appendData(filePath, "pankaj");
			//now file content is "ABCDEDatapankaj"
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void appendData(String filePath, String data) throws IOException {
		RandomAccessFile raFile = new RandomAccessFile(filePath, "rw");
		raFile.seek(raFile.length());
		System.out.println("current pointer = "+raFile.getFilePointer());
		raFile.write(data.getBytes());
		raFile.close();
		
	}

	private static void writeData(String filePath, String data, int seek) throws IOException {
		RandomAccessFile file = new RandomAccessFile(filePath, "rw");
		file.seek(seek);
		file.write(data.getBytes());
		file.close();
	}

	private static byte[] readCharsFromFile(String filePath, int seek, int chars) throws IOException {
		RandomAccessFile file = new RandomAccessFile(filePath, "r");
		file.seek(seek);
		byte[] bytes = new byte[chars];
		file.read(bytes);
		file.close();
		return bytes;
	}

}

That’s all for RandomAccessFile in java.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
December 17, 2019

How about prepending a text at the start of the file without overriding.

- Abhishay

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 8, 2017

    my file path shows error in this program

    - karthi

      Try DigitalOcean for free

      Click below to sign up and get $200 of credit to try our products over 60 days!

      Sign up

      Join the Tech Talk
      Success! Thank you! Please check your email for further details.

      Please complete your information!

      Get our biweekly newsletter

      Sign up for Infrastructure as a Newsletter.

      Hollie's Hub for Good

      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

      Become a contributor

      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

      Welcome to the developer cloud

      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

      Learn more
      DigitalOcean Cloud Control Panel