Java Reference
In-Depth Information
// Read all data from the channel
while (fileChannel.read(buffer) > 0) {
// Flip the buffer before we can read data from it
buffer.flip();
// Display the read data as characters on the console
// Note that we are assuming that a byte represents a
// character, which is not true all the time. In a
// real world application, you should use
// CharsetDecoder to decode the bytes into character
// before you display/use them.
while (buffer.hasRemaining()) {
byte b = buffer.get();
// Assuming a byte represents a character
System.out.print((char) b);
}
// Clear the buffer before next read into it
buffer.clear();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
STRANGE fits of passion have I known:
And I will dare to tell,
But in the lover's ear alone,
What once to me befell.
The steps to write data to a file using a buffer and a channel are as follows:
•
Create an object of
FileOutputStream
.
•
Get a
FileChannel
object using the
getChannel()
method of
FileOutputStream
.
Create a
•
ByteBuffer
object to write data to the file.
•
Fill the
ByteBuffer
with data.
Call the
•
flip()
method of the buffer to get it ready to be read by the channel.
•
Call the
write()
method of the
FileChannel
object by passing the
ByteBuffer
object filled
with data .
close()
method.
Listing 9-8 puts all the above steps together to write the following text to
luci5.txt
file:
•
Close the channel by calling its
In one of those sweet dreams I slept,
Kind Nature's gentlest boon!
And all the while my eyes I kept
On the descending moon.