Java Reference
In-Depth Information
The file is read in the expression used for the while loop condition. The read() method will return -1
when the end-of-file is reached so that will end the loop. Within the loop we have to extract the data
from the buffer, do what we want with it, and then clear the buffer ready for the next read operation.
Getting Data from the Buffer
After the read operation, the buffer's position will point to the byte following the last byte that was read.
Before we attempt to extract any data from the buffer we therefore need to flip the buffer to reset the
position back to the beginning of the data and the limit to the byte following the last byte of data. One
way to extract bytes from the buffer is to use the ByteBuffer object's getChar() method. This will
retrieve a Unicode character from the buffer at the current position and increment the position by two.
This could work like this:
buf.flip();
StringBuffer str = new StringBuffer(buf.remaining()/2);
while(buf.hasRemaining())
str.append(buf.getChar());
System.out.println("String read: "+ str.toString());
This code should replace the comment in the previous fragment that appears at the beginning of the
while loop. We first create a StringBuffer object in which we will assemble the string. This is the
most efficient way to do this - using a String object would result in the creation of a new object each
time we add a character to the string. The remaining() method for the buffer returns the number of
bytes read after the buffer has been flipped, so we can just divide this by 2 to get the number of
characters read. We extract characters one at a time from the buffer in the while loop and append
them to the StringBuffer object. The getChar() method increments the buffer's position by 2 each
time so eventually hasRemaining() will return false ,when all the characters have been extracted,
and the loop will end. We then just convert it to a string and output it on the command line.
This approach works OK but a better way is to use a view buffer of type CharBuffer . The
toString() method for the CharBuffer object will give us the string that it contains directly.
Indeed, we can boil the whole thing down to a single statement:
System.out.println("String read: " +
((ByteBuffer)(buf.flip())).asCharBuffer().toString());
The flip() method returns a reference of type Buffer so we have to cast it to type ByteBuffer to
make it possible to call the asCharBuffer() method for the buffer.
We can assemble these code fragments into a working example.
Try It Out - Reading Text from a File
Here's the code for the complete program:
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
Search WWH ::




Custom Search