RandomAccessFile in Java

Java RandomAccessFile providing a nonsequential access to files. It behaves like a large array of bytes stored in the file system. That means you don't need to start from 1st line and you can jump to anywhere in the file . It's similar to array data structure, Just like you can access any element in array by index you can read any content from file by using file pointer. The real advantage is that once file is opened, it can be read from or written to in a random manner just by using a record number or you can add to the end since you will know how many records are in the file.

Moving Around a RandomAccessFile

The RandomAccessFile class allows us to jump to a certain location in the file by using the seek() method. Once the file pointer has been positioned, data can be read from and written to the file using the DataInput and DataOutput interfaces. These interfaces allow us to read and write data in a platform-independent manner. The current position of the file pointer can be obtained by calling the getFilePointer() method.
RandomAccessFile(File file, String mode)

The above constructor creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.

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.
Example
import java.util.*; import java.io.*; public class TestClass{ public static void main(String[] args) { try { RandomAccessFile raFile =new RandomAccessFile("D://test.txt","rw"); raFile.write("Java Tutorial".getBytes()); //add the content raFile.seek(raFile.getFilePointer()-8); //set pointer backward -8 characters raFile.write("File Class Tutorial ".getBytes()); //write the text where pointer is raFile.seek(0); //set pointer to start of file int i; while((i= raFile.read())!=-1){ System.out.print((char)i); } } catch (IOException e){ e.printStackTrace(); } } }
Output
Java File Class Tutorial