Java Reference
In-Depth Information
The FileChannel object keeps track of the file's current position, and this is initially set to zero,
corresponding to the first byte available from the file. Each read operation increments the channel's file
position by the number of bytes read, so the next read operation will start at that point, assuming you
have not modified the file position by some other means. When you need to change the file position in
the channel - to reread the file for instance - you just call the position() method for the
FileChannel object, with the index position of the byte where you want the next read to start as the
argument to the method. For example, with a reference to a FileChannel object stored in a variable
inChannel , you could reset the file position back to the beginning of the file with the statements:
try {
inChannel.position(0); // Set file position to first byte
} catch(IOException e) {
e.printStackTrace();
}
This method will throw a ClosedChannelException if the channel is closed, or an IOException
if some other error occurs, so you need to put the call in a try block. It can also throw an
IllegalArgumentException if the argument is negative. This is a subclass of
RuntimeException You can legally specify a position beyond the end of the file, but a subsequent
read operation will just return -1 indicating the end-of-file has been reached.
Calling the position() method with no argument specified returns the current file position. This
version of the method can also throw exceptions of type ClosedChannelException and
IOException so you must put the call in a try block or make the calling method declare the
exceptions in a throws clause.
Initial File
Position
File Position
after read
Data in the file
channel.read(buf)
The number of bytes read is determined by the buffer
and will be
limit-position
bytes.
Bytes read
ByteBuffer buf
Initail Buffer
position = 0
Buffer Limit
Buffer position after read
Reading from a File into a Buffer
The amount of data read from a file into a byte buffer is determined by the position and limit for the
buffer when the read operation executes. Bytes are read into the buffer starting at the byte in the buffer
given by its position, and assuming there are sufficient bytes available from the file, limit-position
bytes will be stored in the buffer.
Search WWH ::




Custom Search