Java - RandomAccessFile

This class is used for reading and writing to random access file. A random access file behaves like a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor we do the read write operations. If end-of-file is reached before the desired number of byte has been read than EOFException is thrown. It is a type of IOException.

Constructor

ConstructorDescription
RandomAccessFile(File file, String mode)Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.
RandomAccessFile(String name, String mode)Creates a random access file stream to read from, and optionally to write to, a file with the specified name.

Method

Modifier and TypeMethodMethod
voidclose()It closes this random access file stream and releases any system resources associated with the stream.
FileChannelgetChannel()It returns the unique FileChannel object associated with this file.
intreadInt()It reads a signed 32-bit integer from this file.
StringreadUTF()It reads in a string from this file.
voidseek(long pos)It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
voidwriteDouble(double v)It 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.
voidwriteFloat(float v)It 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.
voidwrite(int b)It writes the specified byte to this file.
intread()It reads a byte of data from this file.
longlength()It returns the length of this file.
voidseek(long pos)It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

Example

The myFile.TXT contains text "This class is used for reading and writing to random access file."

after running the program it will contains

This class is used for reading I love my country and my peoplele.






Latest Courses