Java RandomAccessFile classLast Updated : 9 Feb 2026 The RandomAccessFile class is used to read and write data to a file at any position. It allows accessing a file like an array of bytes. In this chapter, we will learn how to use the RandomAccessFile class to read and write data at any position in a file. What is Java RandomAccessFile Class?The RandomAccessFile class belongs to the java.io package and allows reading and writing data at any location in a file using a file pointer. The file pointer moves automatically after read or write operations. If the end of the file is reached before reading the required bytes, an EOFException is thrown. Java RandomAccessFile Class DeclarationThe declaration of the RandomAccessFile class is as follows: Constructors of RandomAccessFile ClassThe RandomAccessFile class provides constructors to open a file in read or read-write mode. 1. RandomAccessFile(File file, String mode)This constructor creates a random-access file stream to read from, and optionally to write to, the file specified by the File object. Here is the syntax: 2. RandomAccessFile(String name, String mode)This constructor creates a random-access file stream to read from, and optionally to write to, a file with the specified name. Here is the syntax: The mode can be:
Methods of RandomAccessFile ClassThe RandomAccessFile class provides methods to read, write, and control file pointer position. Constructor
Method
Examples of RandomAccessFile ClassThe following examples show how to use the RandomAccessFile class in Java. Example 1: Read Data from File Using RandomAccessFileIn this example, data is read from a file starting from a specific position. Output: This class is used Example 2: Write Data at Specific Position Using RandomAccessFileIn this example, text is written at a specific position in the file. File Content After Execution: This class is used for reading I love my country and my people. Next TopicHow to Create a Zip File in Java |
We request you to subscribe our newsletter for upcoming updates.