Java Reference
In-Depth Information
}
ByteBuffer buf = ByteBuffer.allocate(50);
try (ReadableByteChannel inCh = Files.newByteChannel(file)){
while(inCh.read(buf) != -1) {
System.out.print("String read: " +
((ByteBuffer)(buf.flip())).asCharBuffer().toString());
buf.clear();
// Clear the buffer for the
next read
}
System.out.println("EOF reached.");
} catch(IOException e) {
e.printStackTrace();
}
}
}
ReadAString.java
When you compile and run this, you should get output something like the following:
String read: Garbage in, garbage out.
String read: Garbage in, garbage out.
String read: Garbage in, garbage out.
EOF reached.
The number of lines of output depends on how many times you ran the example that wrote the file.
How It Works
Nothing is new here beyond what I have already discussed. The file contains new line characters so the
print() method generates the output that you see.
If you want to output the length of the file, you could add a statement to call the size() method for the
inCh object:
System.out.println("File contains " +
((SeekableByteChannel)inCh).size() + " bytes.");
For this to compile you will need an import statement for java.nio.channels.SeekableByteChannel .
The newByteChannel() method returns a reference of this type, but it was stored as Read-
ableByteChannel (a subinterface of SeekableByteChannel ) and this type does not specify the size()
method. Immediately before the while loop would be a good place to put it because the size() method
can throw an IOException . You might also like to modify the code to output the buffer's position and
limit before and after the read. This shows quite clearly how these change when the file is read.
Of course, this program works because you have prior knowledge of how long the records are in the file.
If you didn't have this information, you would have to read a chunk of data from the file and then figure
out where each record ended by looking for the \n character that appears at the end of each record. You
get an idea of how you could deal with this kind of situation a little later in this chapter when I go into
reading mixed data from a file.
Search WWH ::




Custom Search