Java Reference
In-Depth Information
This code would replace the comment in the previous fragment that appears at the beginning of the while
loop. You first create a StringBuffer object in which you assemble the string. This is the most efficient
way to do this — using a String object would result in the creation of a new String object each time
you add a character to the string. Of course, because there's no possibility of multiple threads accessing the
string, you could use a StringBuilder object here instead of the StringBuffer object and gain a little
more efficiency. The remaining() method for the buffer returns the number of bytes read after the buffer
has been flipped, so you can just divide this by two to get the number of characters read. You extract char-
acters 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 two each time, so eventually the hasRemaining()
method returns false when all the characters have been extracted, and the loop ends. You then just convert
the StringBuffer to a String object and output the string on the command line.
This approach works okay, but a better way is to use a view buffer of type CharBuffer . The toString()
method for the CharBuffer object gives you the string that it contains directly. Indeed, you 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 you have to cast it to type ByteBuffer to
make it possible to call the asCharBuffer() method for the buffer object. This is necessary because the
asCharBuffer() method is defined in the CharBuffer class, not in the Buffer class.
You 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 to read the charData.txt file that you wrote in the previous
chapter using the BufferStateTrace.java program:
import java.nio.file.*;
import java.nio.channels.ReadableByteChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
public class ReadAString {
public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("charData.txt");
if(!Files.exists(file)) {
System.out.println(file + " does not exist. Terminating
program.");
System.exit(1);;
Search WWH ::




Custom Search