Java RandomAccessFile Example

Filed Under: Java

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.

Comments

  1. karthi says:

    my file path shows error in this program

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages