Random access files permit nonsequential, or random, access to a file's contents. To access a file randomly, you open the file, seek to a particular location, and read from or write to that file.This functionality is possible with the
SeekableByteChannel
interface. TheSeekableByteChannel
interface extends channel I/O with the notion of a current position. Methods allow you to set or query the position and you can then read the data from, or write the data to, that location. The API consists of a few, easy to use, methods:
position
— returns the channel's current position.position(long)
— sets the channel's position.read(ByteBuffer)
— reads bytes into the buffer from the channel.write(ByteBffer)
— writes bytes from the buffer to the channel.truncate(long)
— truncates the file (or other entity) connected to the channel.The Reading and Writing Files with Channel I/O section shows that the
Path.newByteChannel
methods return an instance of aSeekableByteChannel
. On the default file system, you can use that channel as-is, or you can cast it to aFileChannel
giving you access to more advanced features, such as mapping a region of the file directly into memory for faster access, locking a region of the file, or reading and writing bytes from an absolute location without affecting the channel's current position.The following code opens a file for both reading and writing using one of the
newByteChannel
methods. TheSeekableByteChannel
that is returned is cast to aFileChannel
. Twelve bytes are read from the beginning of the file. Then the string "I was here!" is written at that location. The current position into the file is moved to the end and the twelve bytes from the beginning are appended. Finally, the string, "I was here!" is appended and the channel on the file is closed.
String s = "I was here!\n"; byte data[] = s.getBytes(); ByteBuffer out = ByteBuffer.wrap(data); ByteBuffer copy = ByteBuffer.allocate(12); FileChannel fc = null; try { fc = (FileChannel)file.newByteChannel(READ, WRITE); //Read the first 12 bytes of the file. int nread; do { nread = fc.read(copy); } while (nread != -1 && copy.hasRemaining()); //Write "I was here!" at the beginning of the file. fc.position(0); while (out.hasRemaining()) fc.write(out); out.rewind(); //Move to the end of the file. Copy the first 12 bytes to //the end of the file. Then write "I was here!" again. long length = fc.size(); fc.position(length-1); copy.flip(); while (copy.hasRemaining()) fc.write(copy); while (out.hasRemaining()) fc.write(out); } catch (IOException x) { System.out.println("I/O Exception: " + x); } finally { //Close the file. if (fc != null) fc.close(); System.out.println(file + " has been modified!"); }