Java Reference
In-Depth Information
File Position
The position of a file is the index position of where the next byte is to be read or written in the file. The
first byte in a file is at position zero so the value for a file's position is the offset of the next byte from the
beginning. Don't confuse the file position with the position for a buffer that I discussed earlier — the two
are quite independent.
When you write the contents of a buffer to a file using a channel, the byte at the buffer's current position
is written to the file at the file's current position. This is illustrated in Figure 10-10 .
FIGURE 10-10
The file channel object keeps track of the current position in the file. If you created the file stream to
append to the file by using a FileOutputStream constructor with the append mode argument as true then
the file position recorded by the channel for the file starts out at the byte following the last byte. Otherwise,
the initial file position is the first byte of the file. The file position is generally incremented by the number
of bytes written each time you write to the file. There is one exception to this. The SeekableByteChannel
interface declares a write() method that does what is presented in Table 10-10 .
TABLE 10-10 : SeekableByteChannel write() Method
METHOD
DESCRIPTION
This writes the contents of the buffer, buf , to the file at the position specified by the second argu-
ment, and not the file position recorded by the channel. Bytes from the buffer are written starting
at the buffer's current position, and buf.remaining() bytes are written. This does not update the
channel's file position.
write(ByteBuffer
buf, long posi-
tion)
This method can throw any of the following exceptions:
IllegalArgumentException: Thrown if you specify a negative value for the file position.
NonWritableChannelException : Thrown if the file was not opened for writing.
ClosedChannelException : Thrown if the channel is closed.
ClosedByInterruptException : Thrown if another thread interrupts the current thread while the
write operation is in progress.
IOException : Thrown if any other I/O error occurs.
 
 
 
 
Search WWH ::




Custom Search