Java Reference
In-Depth Information
Your first steps are to define a Path object encapsulating the file path and to create a FileChannel object
using the process you saw at the beginning of this chapter.
You create a ByteBuffer object exactly as you saw previously when you were writing the file in Chapter
10. You know that you wrote 50 bytes at a time to the file — you wrote the string "Garbage in, garbage
out.\n" that consists of 25 Unicode characters. However, it's possible that you tried appending to the file
an arbitrary number of times, so you should provide for reading as many Unicode characters as there are in
the file. You can set up the ByteBuffer with exactly the right size for the data from a single write operation
with the following statement:
ByteBuffer buf = ByteBuffer.allocate(50);
The code that you use to read from the file needs to allow for an arbitrary number of 25-character strings
in the file. Of course, it must also allow for the end-of-file being reached while you are reading the file. You
can read from the file into the buffer like this:
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java Stuff").resolve("charData.txt");
ByteBuffer buf = ByteBuffer.allocate(50);
try (ReadableByteChannel inCh = file.newByteChannel()){
while(inCh.read(buf) != -1) {
// Code to extract the data that was read into the buffer...
buf.clear(); // Clear the buffer for the next read
}
System.out.println("EOF reached.");
} catch(IOException e) {
e.printStackTrace();
}
The file is read by calling the read() method for the FileChannel object in the expression that you use
for the while loop condition. The loop continues to read from the file until the read() method returns −1
when the end-of-file is reached. Within the loop you have to extract the data from the buffer, do what you
want with it, and then clear the buffer to be ready for the next read operation.
Getting Data from the Buffer
After each read operation, the buffer's position points to the byte following the last byte that was read. Be-
fore you attempt to extract any data from the buffer, you therefore need to flip the buffer to reset the buffer
position back to the beginning of the data, and the buffer limit to the byte following the last byte of data
that was read. One way to extract bytes from the buffer is to use the getChar() method for the ByteBuffer
object. This retrieves a Unicode character from the buffer at the current position and increments 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());
Search WWH ::




Custom Search