Java Reference
In-Depth Information
The following statements create a file input stream and a channel associated with that
file:
try {
String source = “prices.dat”;
FileInputStream inSource = new FileInputStream(source);
FileChannel inChannel = inSource.getChannel();
} catch (FileNotFoundException fne) {
System.out.println(fne.getMessage());
}
After you have created the file channel, you can find out how many bytes the file con-
tains by calling its size() method. This is necessary if you want to create a byte buffer
to hold the contents of the file.
Bytes are read from a channel into a ByteBuffer with the read( ByteBuffer , long )
method. The first argument is the buffer. The second argument is the current position in
the buffer, which determines where the file's contents will begin to be stored.
The following statements extend the last example by reading a file into a byte buffer
using the inChannel file channel:
long inSize = inChannel.size();
ByteBuffer data = ByteBuffer.allocate( (int)inSize );
inChannel.read(data, 0);
data.position(0);
for (int i = 0; data.remaining() > 0; i++)
System.out.print(data.get() + “ “);
The attempt to read from the channel generates an IOException error if a problem
occurs. Although the byte buffer is the same size as the file, this isn't a requirement. If
you are reading the file into the buffer so that you can modify it, you can allocate a
larger buffer.
The next project you undertake incorporates the new input/output features you have
learned about so far: buffers, character sets, and channels.
The BufferConverter application reads a small file into a byte buffer, displays the con-
tents of the buffer, converts it to a character buffer, and then displays the characters.
Enter the text of Listing 17.4 and save it as BufferConverter.java .
Search WWH ::




Custom Search