java.nio Code Samples
- How do I use a FileChannel to read data into a Buffer?
- How do I copy one file to another file?
- How do I read all lines from a file?
- How do I write data into Buffer using put method?
- How do I clear a buffer using clear method?
- How do I change the buffer mode between write and read?
- How do I read data from a buffer into channel?
- How do I clear a buffer using compact method?
- How do I create a NIO Buffer?
- How do I reread the content of a buffer?
Page 1 of 1 |
Prev
|
Next
How do I use a FileChannel to read data into a Buffer?
The example below show how to use a FileChannel to read some data into a Buffer. We create a FileChannel from a FileInputStream instance. Because a channel reads data into buffer we need to create a ByteBuffer and set its capacity. Read data from a channel into buffer using the FileChannel.read() method.
To read out the data from the buffer we need to flip the buffer first using the Buffer.flip() method. The method will change the buffer from writing-mode into reading-mode. After the entire buffer is read clear the buffer using the clear() method call.