×

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

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

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.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.