Home  >  Core Java

Java RandomAccessFile Example

By Arvind Rai, July 19, 2014
java.io.RandomAccessFile has been introduced in JDK 1.0. RandomAccessFile supports read and write both. Once data is written, RandomAccessFile uses seek() method that gets the pointer from where to start reading. There are different constructors to instantiate the RandomAccessFile.
RandomAccessFile(File file, String mode) : Accepts file object and mode of read and write.
RandomAccessFile(String name, String mode) : Accepts String as file path and mode.

Possible Access Mode
In RandomAccessFile, while instantiating default mode is read only. But we can provide different mode. These modes are
"r" : File is open for read only.
"rw" : File is open for read and write both.
"rws" : Same as rw mode. It also supports to update file content synchronously to device storage.
"rwd" : Same as rw mode that also supports reduced number of IO operation.
RandomAccessFileDemo.java
package com.cp.io;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
	public static void main(String[] args) throws IOException {
		RandomAccessFile raFile =null;
		try {
			raFile = new RandomAccessFile("D:/cp/text.txt","rw");
			int i=0;
			try {
				 //RandomAccessFile writes below text in text.txt
				 raFile.write("This is example.".getBytes());
				 //sets pointer just before "example" text
				 raFile.seek(raFile.getFilePointer()-8);
				 //writes below text just after "This is "
				 raFile.write("RandomAccessFile example".getBytes());
				 //sets pointer at start to read data from start
				 raFile.seek(0);
				 while((i= raFile.read())!=-1){
					System.out.print((char)i);
				 }
			} catch (IOException e) {
				e.printStackTrace();
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally{
			raFile.close();
		}
	}
} 
Output is as below.
This is RandomAccessFile example
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us