×

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

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

Palindrome number program in Java

Write java program to check if a number is palindrome in Java? A number that does not change on reversing is called a palindrome number. In other words, when reversing the...

3 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.