RandomAccessFile

RandomAccessFile encapsulates a random-access file.

It is not derived from InputStream or OutputStream.

Instead, it implements the interfaces DataInput and DataOutput, which define the basic I/O methods.

It implements the Closeable interface.

RandomAccessFile supports positioning requests, you can position the file pointer within the file.

It has these two constructors:

RandomAccessFile(File fileObj, String access) throws FileNotFoundException
fileObj specifies the name of the file to open as a File object.
RandomAccessFile(String filename, String access) throws FileNotFoundException
the name of the file is passed in filename.

access parameter determines what type of file access is permitted.

accessMeaning
rthe file can be read, but not written.
rwopened in read-write mode.
rwsopened for read-write operations and every change (data and metadata) will be immediately written to the physical device.
rwdopened for read-write operations and every change to the file's data will be immediately written to the physical device.

The method seek( ) sets the current position of the file pointer within the file:


void seek(long newPos) throws IOException

newPos specifies the new position, in bytes, of the file pointer from the beginning of the file. After a call to seek( ), the next read or write operation will occur at the new file position.

It includes some additional methods.

One is setLength( ). It has this signature:


void setLength(long len) throws IOException

This method sets the length of the invoking file to that specified by len. This method can be used to lengthen or shorten a file. If the file is lengthened, the added portion is undefined.

Home 
  Java Book 
    File Stream  

RandomAccessFile:
  1. RandomAccessFile
  2. new RandomAccessFile(String fileName, String mode)
  3. RandomAccessFile: close()
  4. RandomAccessFile: getChannel()
  5. RandomAccessFile: getFilePointer()
  6. RandomAccessFile: length()
  7. RandomAccessFile: read(byte[] b)
  8. RandomAccessFile: readBoolean()
  9. RandomAccessFile: readByte()
  10. RandomAccessFile: readChar()
  11. RandomAccessFile: readDouble()
  12. RandomAccessFile: readInt()
  13. RandomAccessFile: readLine()
  14. RandomAccessFile: seek(long pos)
  15. RandomAccessFile: write(byte[] b)
  16. RandomAccessFile: writeBoolean(boolean v)
  17. RandomAccessFile: writeBytes(String s)
  18. RandomAccessFile: writeChars(String s)
  19. RandomAccessFile: writeInt(int v)
  20. RandomAccessFile: writeUTF(String str)