×

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer cursor, which is present in the array, we may do read and write operations. End-of-file exceptions are thrown if they occur before a particular number of bytes are  read. It is an IOException subtype.

Java IO includes the class RandomAccessFile. We must specify the method to open the file when creating a RandomAccessFile instance in Java. For instance, we must use "r" to open the file in read-only mode and "rw" to open it in read-write mode. Data from a random access file can be read or written at any position by using a file pointer. You can use the getFilePointer() function to obtain the current file pointer and the seek(int I method to set its file pointer index. Any index where we write data overrides any data that is already there.

Constructor

RandomAccessFile(File file, String mode)

The file provided by the File parameter is produced as a random access file stream and is used to read from and, potentially, write to the file.

RandomAccessFile(String name, String mode)

Creates one random access file stream that read from and, optionally, writes to a file with the supplied name.

Method

1. Modifier type: void

Method : close()

The random access file stream is shut down, and any system resources used by the stream are released.

2. Modifier type: FileChannel

Method: getChannel

It gives back the particular FileChannel object connected to this file.

3. Modifier type: int

Method : readInt();

a signed 32-bit integer is read from the file

4. Modifier type: String

Method : readUTf()

A string is read from this file and entered.

5. Modifier type: void

Method : seek(long pos)

It establishes the file-pointer offset from the file's start where the following read or write will take place.

6. Modifier type: void

Method : writeDouble(double v)

Using the doubleToLongBits function from the Double class, it transforms the double parameter to a long, which is then written to the file as a 8 number, high byte first.

7. Modifier type: void

 Method : writeFloat(float v)

The function writeFloat(float v) writes the converted float result to the file as a four-bit number, high byte first, utilizing floatToIntBits method from the class Float.

8. Modifier type: void

 Method : write(int b)

It updates this file with the specified byte.

9. Modifier type: int

Method : read()

A byte of information is read from this file.

10. Modifier type: long

Method : length()

It gives back the size of this file.

11. Modifier type: void

Method : seek(long pos)

It establishes the file-pointer offset from the file's start where the following read or write will take place.

Example program

import java.io.IOException;  
import java.io.RandomAccessFile;  
  
public class RandomAccessfile {  
    static final String Filepath ="myFile.txt";  
    public static void main(String[] args) {  
        try {  
            System.out.println(new String(readFromFile(FILEPATH, 1, 10)));  
            writeToFile(Filepath, "Hello people have a good day", 30);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
    private static byte[] readFromFile(String filePath, int pos, int size)  
            throws IOException {  
        RandomAccessFile file = new RandomAccessFile(filePath, "r");  
        file.seek(pos);  
        byte[] bytes = new byte[size];  
        file.read(bytes);  
        file.close();  
        return bytes;  
    }  
    private static void writeToFile(String filePath, String data, int position)  
            throws IOException {  
        RandomAccessFile file = new RandomAccessFile(filePath, "rw");  
        file.seek(position);  
        file.write(data.getBytes());  
        file.close();  
    }  
}  

The sentence "This class is utilized for read and write to random access file" can be found in the file myFile.txt.

Once the software has been executed, it will contain

Example program

import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccess {
	public static void main(String[] args) {
		try {
			String filePath = "/Users/sravani/Downloads/source.txt"; 
			System.out.println(new String(readCharsFromFile(filePath, 4, 6)));
			writeData(filePath, "Data", 4);
			appendData(filePath, "sravani");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private static void appendData(String filePath, String data) throws IOException {
		RandomAccessFile rFile = new RandomAccessFile(filePath, "rw");
		rFile.seek(raFile.length());
		System.out.println("current pointer = "+rFile.getFilePointer());
		rFile.write(data.getBytes());
		rFile.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;
	}


}

Related Topics

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.