RandomAccessFile RandomAccessFile(String, String) in Java

RandomAccessFile(String, String): This method is available in the java.io.RandomAccessFile class of Java.

Syntax:

java.io.RandomAccessFile.RandomAccessFile(String name, String mode) throws FileNotFoundException

This method takes two arguments. This method creates a random access file stream to read from, and optionally to write to, a file with the specified name. A new FileDescriptor object is created to represent the connection to the file.

Parameters: Two parameters are required for this method.

name: the system-dependent file name.

mode: the access mode.

Returns: NA

Throws:

1. IllegalArgumentException - if the mode argument is not equal to one of "r", "rw", "rws", or "rwd".

2. FileNotFoundException - if the mode is "r" but the given string does not denote an existing regular file, or if the mode begins with "rw" but the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file.

3. SecurityException - if a security manager exists and its checkRead method denies read access to the file or the mode is "rw" and the security manager's checkWrite method denies write access to the file.

Approach 1: When no exception

Java

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileRandomAccessFile2 {
    public static void main(String[] args) throws IOException {

        String name = "D:\\hello.txt";
        String mode = "r";
        RandomAccessFile randomAccessFile =
new RandomAccessFile(name, mode);

        System.out.println(randomAccessFile);
        randomAccessFile.close();
    }
}

Output:

java.io.RandomAccessFile@7637f22


Approach 2: IllegalArgumentException

Java

package com.RandomAccessFile;

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileRandomAccessFile2 {
    public static void main(String[] args) throws IOException {

        String name = "D:\\hello.txt";
        String mode = "read";
        RandomAccessFile randomAccessFile =
new RandomAccessFile(name, mode);

        System.out.println(randomAccessFile);
        randomAccessFile.close();
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal mode "read" must be one of "r", "rw", "rws", or "rwd" at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:241) at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:216) at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:129) at com.RandomAccessFile.RandomAccessFileRandomAccessFile2.main(RandomAccessFileRandomAccessFile2.java:11)


Approach 3: FileNotFoundException

Java

package com.RandomAccessFile;

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileRandomAccessFile2 {
    public static void main(String[] args) throws IOException {

        String name = "D:\\hello111111.txt";
        String mode = "r";
        RandomAccessFile randomAccessFile =
new RandomAccessFile(name, mode);

        System.out.println(randomAccessFile);
        randomAccessFile.close();
    }
}

Output:

Exception in thread "main" java.io.FileNotFoundException: D:\hello111111.txt (The system cannot find the file specified) at java.base/java.io.RandomAccessFile.open0(Native Method) at java.base/java.io.RandomAccessFile.open(RandomAccessFile.java:347) at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:261) at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:216) at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:129) at com.RandomAccessFile.RandomAccessFileRandomAccessFile2.main(RandomAccessFileRandomAccessFile2.java:11)


Some other methods of RandomAccessFile

close()This method closes this random access file stream and releases any system resources associated with the stream.

getChannel()This method returns the unique FileChannel object associated with this file.

getFD()This method returns the opaque file descriptor object associated with this stream.

getFilePointer()This method returns the current offset in this file.

length()This method returns the length of this file.

RandomAccessFile(File, String)This method creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. 

RandomAccessFile(String, String)This method creates a random access file stream to read from, and optionally to write to, a file with the specified name.

read()This method reads a byte of data from this file.

read(byte[])This method reads up to b.length bytes of data from this file into an array of bytes.

read(byte[], int, int)This method reads up to len bytes of data from this file into an array of bytes.

readBoolean()This method reads a single byte from the file, starting at the current file pointer.

readByte()This method reads a signed eight-bit value from this file.

readChar()This method reads a character from this file. This method reads two bytes from the file, starting at the current file pointer.

readDouble() This method reads a long value, starting at the current file pointer, as if by the readLong method, and then converts that long to a double using the longBitsToDouble method in class Double.

readFloat()This method reads an int value, starting at the current file pointer, as if by the readInt method, and then converts that int to a float using the intBitsToFloat method in class Float.

readFully(byte[])This method reads b.length bytes from this file into the byte array, starting at the current file pointer. 

readFully(byte[], int, int)This method reads exactly the len bytes from this file into the byte array, starting at the current file pointer.

readInt()This method reads a signed 32-bit integer from this file. This method reads 4 bytes from the file, starting at the current file pointer.

readLine()This method reads the next line of text from this file.

readLong()This method reads a signed 64-bit integer from this file. This method reads eight bytes from the file, starting at the current file pointer.

readShort()This method reads a signed 16-bit number from this file. The method reads two bytes from this file, starting at the current file pointer.

readUnsignedByte()This method reads an unsigned eight-bit number from this file. This method reads a byte from this file, starting at the current file pointer, and returns that byte.

readUnsignedShort()This method reads an unsigned 16-bit number from this file. This method reads two bytes from the file, starting at the current file pointer.

readUTF()This method reads in a string from this file. The string has been encoded using a modified UTF-8 format.

seek(long)This method sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

setLength(long)This method sets the length of this file.

skipBytes(int)This method attempts to skip over n bytes of input discarding the skipped bytes.

write(byte[])This method writes b.length bytes from the specified byte array to this file, starting at the current file pointer.

write(int)This method writes the specified byte to this file.

write(byte[], int, int)This method writes len bytes from the specified byte array starting at offset off to this file.

writeBoolean(boolean)This method writes a boolean to the file as a one-byte value.

writeByte(int)This method writes a byte to the file as a one-byte value.

writeBytes(String)This method writes the string to the file as a sequence of bytes.

writeChar(int v)This method writes a char to the file as a two-byte value, high byte first.

writeChars(String)This method writes a string to the file as a sequence of characters.

writeDouble(double)This method converts the double argument to a long using the doubleToLongBits method in class Double and then writes that long value to the file as an eight-byte quantity, high byte first.

writeFloat(float)This method converts the float argument to an int using the floatToIntBits method in class Float and then writes that int value to the file as a four-byte quantity, high byte first.

writeInt(int)This method writes an int to the file as four bytes, the high byte first.

writeLong(long)This method writes a long to the file as eight bytes, high byte first.

writeShort(int)This method writes a short to the file as two bytes, the high byte first.

writeUTF(String)This method writes a string to the file using modified UTF-8 encoding in a machine-independent manner.

RandomAccessFile RandomAccessFile(File, String) in Java

RandomAccessFile(File, String): This method is available in the java.io.RandomAccessFile class of Java.

Syntax:

java.io.RandomAccessFile.RandomAccessFile(File file, String mode) throws FileNotFoundException

This method takes two arguments. This method creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. A new FileDescriptor object is created to represent this file connection.

1. "r": Open for reading only. Invoking any of the writing methods of the resulting object will cause a java.io.IOException to be thrown.

2. "rw": Open for reading and writing. If the file does not already exist then an attempt will be made to create it.

3. "rws": Open for reading and writing, as with "rw", and also require that every update to the file's content or metadata be written synchronously to the underlying storage device.

4. "rwd": Open for reading and writing, as with "rw", and also require that every update to the file's content be written synchronously to the underlying storage device.

Parameters: Two parameters are required for this method.

file: the file object.

mode: the access mode, as described above.

Throws:

1. IllegalArgumentException - if the mode argument is not equal to one of "r", "rw", "rws", or "rwd".

2. FileNotFoundException - if the mode is "r" but the given file object does not denote an existing regular file, or if the mode begins with "rw" but the given file object does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file.

3. SecurityException - if a security manager exists and its checkRead method denies read access to the file or the mode is "rw" and the security manager's checkWrite method denies write access to the file.

Approach 1: When no exception

Java

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileRandomAccessFile {
    public static void main(String[] args) throws IOException {

        File file = new File("D:\\hello.txt");
        String mode = "r";
        RandomAccessFile randomAccessFile =
new RandomAccessFile(file, mode);
        System.out.println(randomAccessFile);
        randomAccessFile.close();
    }
}

Output:

java.io.RandomAccessFile@7637f22


Approach 2: IllegalArgumentException

Java

package com.RandomAccessFile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileRandomAccessFile {
    public static void main(String[] args) throws IOException {

        File file = new File("D:\\hello.txt");
        String mode = "read";
        RandomAccessFile randomAccessFile =
new RandomAccessFile(file, mode);
        System.out.println(randomAccessFile);
        randomAccessFile.close();
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal mode "read" must be one of "r", "rw", "rws", or "rwd" at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:241) at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:216) at com.RandomAccessFile.RandomAccessFileRandomAccessFile.main(RandomAccessFileRandomAccessFile.java:12)


Approach 3: FileNotFoundException 

Java

package com.RandomAccessFile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileRandomAccessFile {
    public static void main(String[] args) throws IOException {

        File file = new File("D:\\hello111111.txt");
        String mode = "r";
        RandomAccessFile randomAccessFile =
new RandomAccessFile(file, mode);
        System.out.println(randomAccessFile);
        randomAccessFile.close();
    }
}

Output:

Exception in thread "main" java.io.FileNotFoundException: D:\hello111111.txt (The system cannot find the file specified) at java.base/java.io.RandomAccessFile.open0(Native Method) at java.base/java.io.RandomAccessFile.open(RandomAccessFile.java:347) at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:261) at java.base/java.io.RandomAccessFile.<init>(RandomAccessFile.java:216) at com.RandomAccessFile.RandomAccessFileRandomAccessFile.main(RandomAccessFileRandomAccessFile.java:12)


Some other methods of RandomAccessFile

close()This method closes this random access file stream and releases any system resources associated with the stream.

getChannel()This method returns the unique FileChannel object associated with this file.

getFD()This method returns the opaque file descriptor object associated with this stream.

getFilePointer()This method returns the current offset in this file.

length()This method returns the length of this file.

RandomAccessFile(File, String)This method creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. 

RandomAccessFile(String, String)This method creates a random access file stream to read from, and optionally to write to, a file with the specified name.

read()This method reads a byte of data from this file.

read(byte[])This method reads up to b.length bytes of data from this file into an array of bytes.

read(byte[], int, int)This method reads up to len bytes of data from this file into an array of bytes.

readBoolean()This method reads a single byte from the file, starting at the current file pointer.

readByte()This method reads a signed eight-bit value from this file.

readChar()This method reads a character from this file. This method reads two bytes from the file, starting at the current file pointer.

readDouble() This method reads a long value, starting at the current file pointer, as if by the readLong method, and then converts that long to a double using the longBitsToDouble method in class Double.

readFloat()This method reads an int value, starting at the current file pointer, as if by the readInt method, and then converts that int to a float using the intBitsToFloat method in class Float.

readFully(byte[])This method reads b.length bytes from this file into the byte array, starting at the current file pointer. 

readFully(byte[], int, int)This method reads exactly the len bytes from this file into the byte array, starting at the current file pointer.

readInt()This method reads a signed 32-bit integer from this file. This method reads 4 bytes from the file, starting at the current file pointer.

readLine()This method reads the next line of text from this file.

readLong()This method reads a signed 64-bit integer from this file. This method reads eight bytes from the file, starting at the current file pointer.

readShort()This method reads a signed 16-bit number from this file. The method reads two bytes from this file, starting at the current file pointer.

readUnsignedByte()This method reads an unsigned eight-bit number from this file. This method reads a byte from this file, starting at the current file pointer, and returns that byte.

readUnsignedShort()This method reads an unsigned 16-bit number from this file. This method reads two bytes from the file, starting at the current file pointer.

readUTF()This method reads in a string from this file. The string has been encoded using a modified UTF-8 format.

seek(long)This method sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

setLength(long)This method sets the length of this file.

skipBytes(int)This method attempts to skip over n bytes of input discarding the skipped bytes.

write(byte[])This method writes b.length bytes from the specified byte array to this file, starting at the current file pointer.

write(int)This method writes the specified byte to this file.

write(byte[], int, int)This method writes len bytes from the specified byte array starting at offset off to this file.

writeBoolean(boolean)This method writes a boolean to the file as a one-byte value.

writeByte(int)This method writes a byte to the file as a one-byte value.

writeBytes(String)This method writes the string to the file as a sequence of bytes.

writeChar(int v)This method writes a char to the file as a two-byte value, high byte first.

writeChars(String)This method writes a string to the file as a sequence of characters.

writeDouble(double)This method converts the double argument to a long using the doubleToLongBits method in class Double and then writes that long value to the file as an eight-byte quantity, high byte first.

writeFloat(float)This method converts the float argument to an int using the floatToIntBits method in class Float and then writes that int value to the file as a four-byte quantity, high byte first.

writeInt(int)This method writes an int to the file as four bytes, the high byte first.

writeLong(long)This method writes a long to the file as eight bytes, high byte first.

writeShort(int)This method writes a short to the file as two bytes, the high byte first.

writeUTF(String)This method writes a string to the file using modified UTF-8 encoding in a machine-independent manner.

RandomAccessFile length() in Java

length(): This method is available in the java.io.RandomAccessFile class of Java.

Syntax:

long java.io.RandomAccessFile.length() throws IOException

This method returns the length of this file.

Parameters: NA

Returns: the length of this file, measured in bytes.

Throws:

1. IOException - if an I/O error occurs.

Approach

Java

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFilelength {
    public static void main(String[] args) throws IOException {

        File file = new File("D:\\hello.txt");
        String mode = "r";
        RandomAccessFile randomAccessFile =
new RandomAccessFile(file, mode);

        System.out.println(randomAccessFile.length());
        randomAccessFile.close();
    }
}

Output:

0


Some other methods of RandomAccessFile

close()This method closes this random access file stream and releases any system resources associated with the stream.

getChannel()This method returns the unique FileChannel object associated with this file.

getFD()This method returns the opaque file descriptor object associated with this stream.

getFilePointer()This method returns the current offset in this file.

length()This method returns the length of this file.

RandomAccessFile(File, String)This method creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. 

RandomAccessFile(String, String)This method creates a random access file stream to read from, and optionally to write to, a file with the specified name.

read()This method reads a byte of data from this file.

read(byte[])This method reads up to b.length bytes of data from this file into an array of bytes.

read(byte[], int, int)This method reads up to len bytes of data from this file into an array of bytes.

readBoolean()This method reads a single byte from the file, starting at the current file pointer.

readByte()This method reads a signed eight-bit value from this file.

readChar()This method reads a character from this file. This method reads two bytes from the file, starting at the current file pointer.

readDouble() This method reads a long value, starting at the current file pointer, as if by the readLong method, and then converts that long to a double using the longBitsToDouble method in class Double.

readFloat()This method reads an int value, starting at the current file pointer, as if by the readInt method, and then converts that int to a float using the intBitsToFloat method in class Float.

readFully(byte[])This method reads b.length bytes from this file into the byte array, starting at the current file pointer. 

readFully(byte[], int, int)This method reads exactly the len bytes from this file into the byte array, starting at the current file pointer.

readInt()This method reads a signed 32-bit integer from this file. This method reads 4 bytes from the file, starting at the current file pointer.

readLine()This method reads the next line of text from this file.

readLong()This method reads a signed 64-bit integer from this file. This method reads eight bytes from the file, starting at the current file pointer.

readShort()This method reads a signed 16-bit number from this file. The method reads two bytes from this file, starting at the current file pointer.

readUnsignedByte()This method reads an unsigned eight-bit number from this file. This method reads a byte from this file, starting at the current file pointer, and returns that byte.

readUnsignedShort()This method reads an unsigned 16-bit number from this file. This method reads two bytes from the file, starting at the current file pointer.

readUTF()This method reads in a string from this file. The string has been encoded using a modified UTF-8 format.

seek(long)This method sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

setLength(long)This method sets the length of this file.

skipBytes(int)This method attempts to skip over n bytes of input discarding the skipped bytes.

write(byte[])This method writes b.length bytes from the specified byte array to this file, starting at the current file pointer.

write(int)This method writes the specified byte to this file.

write(byte[], int, int)This method writes len bytes from the specified byte array starting at offset off to this file.

writeBoolean(boolean)This method writes a boolean to the file as a one-byte value.

writeByte(int)This method writes a byte to the file as a one-byte value.

writeBytes(String)This method writes the string to the file as a sequence of bytes.

writeChar(int v)This method writes a char to the file as a two-byte value, high byte first.

writeChars(String)This method writes a string to the file as a sequence of characters.

writeDouble(double)This method converts the double argument to a long using the doubleToLongBits method in class Double and then writes that long value to the file as an eight-byte quantity, high byte first.

writeFloat(float)This method converts the float argument to an int using the floatToIntBits method in class Float and then writes that int value to the file as a four-byte quantity, high byte first.

writeInt(int)This method writes an int to the file as four bytes, the high byte first.

writeLong(long)This method writes a long to the file as eight bytes, high byte first.

writeShort(int)This method writes a short to the file as two bytes, the high byte first.

writeUTF(String)This method writes a string to the file using modified UTF-8 encoding in a machine-independent manner.