Java Reference
In-Depth Information
try (/* ... create channel inCh... */){
// ...
inCh.position(0); // Set file position to first byte
} catch(IOException e) {
e.printStackTrace();
}
This method throws 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 IllegalArgumentEx-
ception if the argument you supply to the method is negative. IllegalArgumentException is a subclass
of RuntimeException . You can legally specify a position beyond the end of the file, but a subsequent read
operation just returns −1, indicating that the end-of-file has been reached.
Calling the position() method with no argument returns the current file position. You can use this to
record a file position that you want to return to later in a variable. 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.
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, as Figure 11-1 illustrates. Bytes are read into the buffer starting at
the byte in the buffer given by its position; assuming sufficient bytes are available from the file, a total of
limit-position bytes from the file are stored in the buffer.
FIGURE 11-1
You'll see some other channel read() methods later that you can use to read data from a particular point
in a file.
Reading a Text File
You can now attempt to read the charData.txt file that you wrote using the BufferStateTrace example
in the previous chapter. You wrote this file as Unicode characters, so you must take this into account when
interpreting the contents of the file. Of course, all files are read as a series of bytes. It's how you interpret
those bytes that determines whether or not you get something that makes sense.
 
 
Search WWH ::




Custom Search