Class RandomAccessFile
- java.lang.Object
-
- java.io.RandomAccessFile
-
- All Implemented Interfaces:
Closeable,DataInput,DataOutput,AutoCloseable
public class RandomAccessFile extends Object implements DataInput, DataOutput, Closeable
Allows reading from and writing to a file in a random-access manner. This is different from the uni-directional sequential access that aFileInputStreamorFileOutputStreamprovides. If the file is opened in read/write mode, write operations are available as well. The position of the next read or write operation can be moved forwards and backwards after every operation.
-
-
Constructor Summary
Constructors Constructor Description RandomAccessFile(File file, String mode)Constructs a newRandomAccessFilebased onfileand opens it according to the access string inmode.RandomAccessFile(String fileName, String mode)Constructs a newRandomAccessFilebased on the file namedfileNameand opens it according to the access string inmode.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidclose()Closes this file.protected voidfinalize()Invoked when the garbage collector has detected that this instance is no longer reachable.FileChannelgetChannel()Gets this file'sFileChannelobject.FileDescriptorgetFD()Gets this file'sFileDescriptor.longgetFilePointer()Gets the current position within this file.longlength()Returns the length of this file in bytes.intread()Reads a single byte from the current position in this file and returns it as an integer in the range from 0 to 255.intread(byte[] buffer)Reads bytes from the current position in this file and stores them in the byte arraybuffer.intread(byte[] buffer, int byteOffset, int byteCount)Reads up tobyteCountbytes from the current position in this file and stores them in the byte arraybufferstarting atbyteOffset.booleanreadBoolean()Reads a boolean from the current position in this file.bytereadByte()Reads an 8-bit byte from the current position in this file.charreadChar()Reads a big-endian 16-bit character from the current position in this file.doublereadDouble()Reads a big-endian 64-bit double from the current position in this file.floatreadFloat()Reads a big-endian 32-bit float from the current position in this file.voidreadFully(byte[] dst)Equivalent toreadFully(dst, 0, dst.length);.voidreadFully(byte[] dst, int offset, int byteCount)ReadsbyteCountbytes from this stream and stores them in the byte arraydststarting atoffset.intreadInt()Reads a big-endian 32-bit integer from the current position in this file.StringreadLine()Reads a line of text form the current position in this file.longreadLong()Reads a big-endian 64-bit long from the current position in this file.shortreadShort()Reads a big-endian 16-bit short from the current position in this file.intreadUnsignedByte()Reads an unsigned 8-bit byte from the current position in this file and returns it as an integer.intreadUnsignedShort()Reads an unsigned big-endian 16-bit short from the current position in this file and returns it as an integer.StringreadUTF()Reads a string that is encoded inmodified UTF-8from this file.voidseek(long offset)Moves this file's file pointer to a new position, from where followingread,writeorskipoperations are done.voidsetLength(long newLength)Sets the length of this file tonewLength.intskipBytes(int count)Skips overcountbytes in this file.voidwrite(byte[] buffer)Writes the entire contents of the byte arraybufferto this file, starting at the current file pointer.voidwrite(byte[] buffer, int byteOffset, int byteCount)WritesbyteCountbytes from the byte arraybufferto this file, starting at the current file pointer and usingbyteOffsetas the first position withinbufferto get bytes.voidwrite(int oneByte)Writes a byte to this file, starting at the current file pointer.voidwriteBoolean(boolean val)Writes a boolean to this file as a single byte (1 for true, 0 for false), starting at the current file pointer.voidwriteByte(int val)Writes an 8-bit byte to this file, starting at the current file pointer.voidwriteBytes(String str)Writes the low order 8-bit bytes from a string to this file, starting at the current file pointer.voidwriteChar(int val)Writes a big-endian 16-bit character to this file, starting at the current file pointer.voidwriteChars(String str)Writes big-endian 16-bit characters fromstrto this file, starting at the current file pointer.voidwriteDouble(double val)Writes a big-endian 64-bit double to this file, starting at the current file pointer.voidwriteFloat(float val)Writes a big-endian 32-bit float to this file, starting at the current file pointer.voidwriteInt(int val)Writes a big-endian 32-bit integer to this file, starting at the current file pointer.voidwriteLong(long val)Writes a big-endian 64-bit long to this file, starting at the current file pointer.voidwriteShort(int val)Writes a big-endian 16-bit short to this file, starting at the current file pointer.voidwriteUTF(String str)Writes a string encoded withmodified UTF-8to this file, starting at the current file pointer.
-
-
-
Constructor Detail
-
RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
Constructs a newRandomAccessFilebased onfileand opens it according to the access string inmode.modemay have one of following values:"r"The file is opened in read-only mode. An IOExceptionis thrown if any of thewritemethods is called."rw"The file is opened for reading and writing. If the file does not exist, it will be created. "rws"The file is opened for reading and writing. Every change of the file's content or metadata must be written synchronously to the target device. "rwd"The file is opened for reading and writing. Every change of the file's content must be written synchronously to the target device. - Parameters:
file- the file to open.mode- the file access mode, either"r","rw","rws"or"rwd".- Throws:
FileNotFoundException- if the file cannot be opened or created according tomode.IllegalArgumentException- ifmodeis not"r","rw","rws"or"rwd".
-
RandomAccessFile
public RandomAccessFile(String fileName, String mode) throws FileNotFoundException
Constructs a newRandomAccessFilebased on the file namedfileNameand opens it according to the access string inmode. The file path may be specified absolutely or relative to the system property"user.dir".- Parameters:
fileName- the name of the file to open.mode- the file access mode, either"r","rw","rws"or"rwd".- Throws:
FileNotFoundException- if the file cannot be opened or created according tomode.IllegalArgumentException- ifmodeis not"r","rw","rws"or"rwd".
-
-
Method Detail
-
close
public void close() throws IOExceptionCloses this file.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException- if an error occurs while closing this file.
-
finalize
protected void finalize() throws ThrowableDescription copied from class:ObjectInvoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.Note that objects that override
finalizeare significantly more expensive than objects that don't. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it's better to provide an explicitclosemethod (and implementCloseable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like aBigIntegerwhere typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.If you must use finalizers, consider at least providing your own
ReferenceQueueand having your own thread process that queue.Unlike constructors, finalizers are not automatically chained. You are responsible for calling
super.finalize()yourself.Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, "Avoid finalizers" for more.
-
getChannel
public final FileChannel getChannel()
Gets this file'sFileChannelobject.The file channel's
positionis the same as this file's file pointer offset (seegetFilePointer()). Any changes made to this file's file pointer offset are also visible in the file channel's position and vice versa. Closing the channel closes the RandomAccessFile as well. The instance of FileChannel returned is always the same even if the RandomAccessFile or the FileChannel have been closed.- Returns:
- this file's file channel instance.
-
getFD
public final FileDescriptor getFD() throws IOException
Gets this file'sFileDescriptor. This represents the operating system resource for this random access file.- Returns:
- this file's file descriptor object.
- Throws:
IOException- if an error occurs while getting the file descriptor of this file.
-
getFilePointer
public long getFilePointer() throws IOExceptionGets the current position within this file. All reads and writes take place at the current file pointer position.- Returns:
- the current offset in bytes from the beginning of the file.
- Throws:
IOException- if an error occurs while getting the file pointer of this file.
-
length
public long length() throws IOExceptionReturns the length of this file in bytes.- Returns:
- the file's length in bytes.
- Throws:
IOException- if this file is closed or some other I/O error occurs.
-
read
public int read() throws IOExceptionReads a single byte from the current position in this file and returns it as an integer in the range from 0 to 255. Returns -1 if the end of the file has been reached. Blocks until one byte has been read, the end of the file is detected, or an exception is thrown.- Returns:
- the byte read or -1 if the end of the file has been reached.
- Throws:
IOException- if this file is closed or another I/O error occurs.
-
read
public int read(byte[] buffer) throws IOExceptionReads bytes from the current position in this file and stores them in the byte arraybuffer. The maximum number of bytes read corresponds to the size ofbuffer. Blocks until at least one byte has been read, the end of the file is detected, or an exception is thrown. Returns the number of bytes actually read or -1 if the end of the file has been reached. See alsoreadFully(byte[]).- Throws:
IOException- if this file is closed or another I/O error occurs.
-
read
public int read(byte[] buffer, int byteOffset, int byteCount) throws IOExceptionReads up tobyteCountbytes from the current position in this file and stores them in the byte arraybufferstarting atbyteOffset. Blocks until at least one byte has been read, the end of the file is detected, or an exception is thrown. Returns the number of bytes actually read or -1 if the end of the stream has been reached. See alsoreadFully(byte[]).- Throws:
IndexOutOfBoundsException- ifbyteOffset < 0 || byteCount < 0 || byteOffset + byteCount > buffer.length.IOException- if this file is closed or another I/O error occurs.
-
readBoolean
public final boolean readBoolean() throws IOExceptionReads a boolean from the current position in this file. Blocks until one byte has been read, the end of the file is reached or an exception is thrown.- Specified by:
readBooleanin interfaceDataInput- Returns:
- the next boolean value from this file.
- Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.- See Also:
writeBoolean(boolean)
-
readByte
public final byte readByte() throws IOExceptionReads an 8-bit byte from the current position in this file. Blocks until one byte has been read, the end of the file is reached or an exception is thrown.- Specified by:
readBytein interfaceDataInput- Returns:
- the next signed 8-bit byte value from this file.
- Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.- See Also:
writeBoolean(boolean)
-
readChar
public final char readChar() throws IOExceptionReads a big-endian 16-bit character from the current position in this file. Blocks until two bytes have been read, the end of the file is reached or an exception is thrown.- Specified by:
readCharin interfaceDataInput- Returns:
- the next char value from this file.
- Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.- See Also:
writeChar(int)
-
readDouble
public final double readDouble() throws IOExceptionReads a big-endian 64-bit double from the current position in this file. Blocks until eight bytes have been read, the end of the file is reached or an exception is thrown.- Specified by:
readDoublein interfaceDataInput- Returns:
- the next double value from this file.
- Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.- See Also:
writeDouble(double)
-
readFloat
public final float readFloat() throws IOExceptionReads a big-endian 32-bit float from the current position in this file. Blocks until four bytes have been read, the end of the file is reached or an exception is thrown.- Specified by:
readFloatin interfaceDataInput- Returns:
- the next float value from this file.
- Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.- See Also:
writeFloat(float)
-
readFully
public final void readFully(byte[] dst) throws IOExceptionEquivalent toreadFully(dst, 0, dst.length);.- Specified by:
readFullyin interfaceDataInput- Throws:
IOException
-
readFully
public final void readFully(byte[] dst, int offset, int byteCount) throws IOExceptionReadsbyteCountbytes from this stream and stores them in the byte arraydststarting atoffset. IfbyteCountis zero, then this method returns without reading any bytes. Otherwise, this method blocks untilbyteCountbytes have been read. If insufficient bytes are available,EOFExceptionis thrown. If an I/O error occurs,IOExceptionis thrown. When an exception is thrown, some bytes may have been consumed from the stream and written into the array.- Specified by:
readFullyin interfaceDataInput- Parameters:
dst- the byte array into which the data is read.offset- the offset indstat which to store the bytes.byteCount- the number of bytes to read.- Throws:
EOFException- if the end of the source stream is reached before enough bytes have been read.IndexOutOfBoundsException- ifoffset < 0orbyteCount < 0, oroffset + byteCount > dst.length.IOException- if a problem occurs while reading from this stream.NullPointerException- ifdstis null.
-
readInt
public final int readInt() throws IOExceptionReads a big-endian 32-bit integer from the current position in this file. Blocks until four bytes have been read, the end of the file is reached or an exception is thrown.- Specified by:
readIntin interfaceDataInput- Returns:
- the next int value from this file.
- Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.- See Also:
writeInt(int)
-
readLine
public final String readLine() throws IOException
Reads a line of text form the current position in this file. A line is represented by zero or more characters followed by'\n','\r',"\r\n"or the end of file marker. The string does not include the line terminating sequence.Blocks until a line terminating sequence has been read, the end of the file is reached or an exception is thrown.
- Specified by:
readLinein interfaceDataInput- Returns:
- the contents of the line or
nullif no characters have been read before the end of the file has been reached. - Throws:
IOException- if this file is closed or another I/O error occurs.
-
readLong
public final long readLong() throws IOExceptionReads a big-endian 64-bit long from the current position in this file. Blocks until eight bytes have been read, the end of the file is reached or an exception is thrown.- Specified by:
readLongin interfaceDataInput- Returns:
- the next long value from this file.
- Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.- See Also:
writeLong(long)
-
readShort
public final short readShort() throws IOExceptionReads a big-endian 16-bit short from the current position in this file. Blocks until two bytes have been read, the end of the file is reached or an exception is thrown.- Specified by:
readShortin interfaceDataInput- Returns:
- the next short value from this file.
- Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.- See Also:
writeShort(int)
-
readUnsignedByte
public final int readUnsignedByte() throws IOExceptionReads an unsigned 8-bit byte from the current position in this file and returns it as an integer. Blocks until one byte has been read, the end of the file is reached or an exception is thrown.- Specified by:
readUnsignedBytein interfaceDataInput- Returns:
- the next unsigned byte value from this file as an int.
- Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.- See Also:
writeByte(int)
-
readUnsignedShort
public final int readUnsignedShort() throws IOExceptionReads an unsigned big-endian 16-bit short from the current position in this file and returns it as an integer. Blocks until two bytes have been read, the end of the file is reached or an exception is thrown.- Specified by:
readUnsignedShortin interfaceDataInput- Returns:
- the next unsigned short value from this file as an int.
- Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.- See Also:
writeShort(int)
-
readUTF
public final String readUTF() throws IOException
Reads a string that is encoded inmodified UTF-8from this file. The number of bytes that must be read for the complete string is determined by the first two bytes read from the file. Blocks until all required bytes have been read, the end of the file is reached or an exception is thrown.- Specified by:
readUTFin interfaceDataInput- Returns:
- the next string encoded in
modified UTF-8from this file. - Throws:
EOFException- if the end of this file is detected.IOException- if this file is closed or another I/O error occurs.UTFDataFormatException- if the bytes read cannot be decoded into a character string.- See Also:
writeUTF(String)
-
seek
public void seek(long offset) throws IOExceptionMoves this file's file pointer to a new position, from where followingread,writeorskipoperations are done. The position may be greater than the current length of the file, but the file's length will only change if the moving of the pointer is followed by awriteoperation.- Parameters:
offset- the new file pointer position.- Throws:
IOException- if this file is closed,pos < 0or another I/O error occurs.
-
setLength
public void setLength(long newLength) throws IOExceptionSets the length of this file tonewLength. If the current file is smaller, it is expanded but the contents from the previous end of the file to the new end are undefined. The file is truncated if its current size is bigger thannewLength. If the current file pointer position is in the truncated part, it is set to the end of the file.- Parameters:
newLength- the new file length in bytes.- Throws:
IllegalArgumentException- ifnewLength < 0.IOException- if this file is closed or another I/O error occurs.
-
skipBytes
public int skipBytes(int count) throws IOExceptionSkips overcountbytes in this file. Less thancountbytes are skipped if the end of the file is reached or an exception is thrown during the operation. Nothing is done ifcountis negative.- Specified by:
skipBytesin interfaceDataInput- Parameters:
count- the number of bytes to skip.- Returns:
- the number of bytes actually skipped.
- Throws:
IOException- if this file is closed or another I/O error occurs.
-
write
public void write(byte[] buffer) throws IOExceptionWrites the entire contents of the byte arraybufferto this file, starting at the current file pointer.- Specified by:
writein interfaceDataOutput- Parameters:
buffer- the buffer to write.- Throws:
IOException- if an I/O error occurs while writing to this file.
-
write
public void write(byte[] buffer, int byteOffset, int byteCount) throws IOExceptionWritesbyteCountbytes from the byte arraybufferto this file, starting at the current file pointer and usingbyteOffsetas the first position withinbufferto get bytes.- Specified by:
writein interfaceDataOutput- Parameters:
buffer- the buffer to write.byteOffset- the index of the first byte inbufferto write.byteCount- the number of bytes from thebufferto write.- Throws:
IndexOutOfBoundsException- ifbyteCount < 0,byteOffset < 0orbyteCount + byteOffsetis greater than the size ofbuffer.IOException- if an I/O error occurs while writing to this file.
-
write
public void write(int oneByte) throws IOExceptionWrites a byte to this file, starting at the current file pointer. Only the least significant byte of the integeroneByteis written.- Specified by:
writein interfaceDataOutput- Parameters:
oneByte- the byte to write to this file.- Throws:
IOException- if this file is closed or another I/O error occurs.- See Also:
read()
-
writeBoolean
public final void writeBoolean(boolean val) throws IOExceptionWrites a boolean to this file as a single byte (1 for true, 0 for false), starting at the current file pointer.- Specified by:
writeBooleanin interfaceDataOutput- Parameters:
val- the boolean to write to this file.- Throws:
IOException- if this file is closed or another I/O error occurs.- See Also:
readBoolean()
-
writeByte
public final void writeByte(int val) throws IOExceptionWrites an 8-bit byte to this file, starting at the current file pointer. Only the least significant byte of the integervalis written.- Specified by:
writeBytein interfaceDataOutput- Parameters:
val- the byte to write to this file.- Throws:
IOException- if this file is closed or another I/O error occurs.- See Also:
readByte(),readUnsignedByte()
-
writeBytes
public final void writeBytes(String str) throws IOException
Writes the low order 8-bit bytes from a string to this file, starting at the current file pointer.- Specified by:
writeBytesin interfaceDataOutput- Parameters:
str- the string containing the bytes to write to this file- Throws:
IOException- if an I/O error occurs while writing to this file.
-
writeChar
public final void writeChar(int val) throws IOExceptionWrites a big-endian 16-bit character to this file, starting at the current file pointer. Only the two least significant bytes of the integervalare written, with the high byte first.- Specified by:
writeCharin interfaceDataOutput- Parameters:
val- the char to write to this file.- Throws:
IOException- if an I/O error occurs while writing to this file.- See Also:
readChar()
-
writeChars
public final void writeChars(String str) throws IOException
Writes big-endian 16-bit characters fromstrto this file, starting at the current file pointer.- Specified by:
writeCharsin interfaceDataOutput- Parameters:
str- the string to write to this file.- Throws:
IOException- if an I/O error occurs while writing to this file.- See Also:
readChar()
-
writeDouble
public final void writeDouble(double val) throws IOExceptionWrites a big-endian 64-bit double to this file, starting at the current file pointer. The bytes are those returned byDouble.doubleToLongBits(double), meaning a canonical NaN is used.- Specified by:
writeDoublein interfaceDataOutput- Parameters:
val- the double to write to this file.- Throws:
IOException- if an I/O error occurs while writing to this file.- See Also:
readDouble()
-
writeFloat
public final void writeFloat(float val) throws IOExceptionWrites a big-endian 32-bit float to this file, starting at the current file pointer. The bytes are those returned byFloat.floatToIntBits(float), meaning a canonical NaN is used.- Specified by:
writeFloatin interfaceDataOutput- Parameters:
val- the float to write to this file.- Throws:
IOException- if an I/O error occurs while writing to this file.- See Also:
readFloat()
-
writeInt
public final void writeInt(int val) throws IOExceptionWrites a big-endian 32-bit integer to this file, starting at the current file pointer.- Specified by:
writeIntin interfaceDataOutput- Parameters:
val- the int to write to this file.- Throws:
IOException- if an I/O error occurs while writing to this file.- See Also:
readInt()
-
writeLong
public final void writeLong(long val) throws IOExceptionWrites a big-endian 64-bit long to this file, starting at the current file pointer.- Specified by:
writeLongin interfaceDataOutput- Parameters:
val- the long to write to this file.- Throws:
IOException- if an I/O error occurs while writing to this file.- See Also:
readLong()
-
writeShort
public final void writeShort(int val) throws IOExceptionWrites a big-endian 16-bit short to this file, starting at the current file pointer. Only the two least significant bytes of the integervalare written.- Specified by:
writeShortin interfaceDataOutput- Parameters:
val- the short to write to this file.- Throws:
IOException- if an I/O error occurs while writing to this file.- See Also:
readShort(),DataInput.readUnsignedShort()
-
writeUTF
public final void writeUTF(String str) throws IOException
Writes a string encoded withmodified UTF-8to this file, starting at the current file pointer.- Specified by:
writeUTFin interfaceDataOutput- Parameters:
str- the string to write inmodified UTF-8format.- Throws:
IOException- if an I/O error occurs while writing to this file.UTFDataFormatException- if the encoded string is longer than 65535 bytes.- See Also:
readUTF()
-
-