Java RandomAccessFile Example
November 19, 2023
Java RandomAccessFile
supports read and write both to a random access file that behaves like a large array of bytes stored in the file system. 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 Modes
In RandomAccessFile, default mode is read only. We can provide different mode. These modes are as below.
"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.
Example
RandomAccessFileDemo.javapackage 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(); } } }
This is RandomAccessFile example