Reading a file using Channel and Buffer
suggest changeChannel
uses a Buffer
to read/write data. A buffer is a fixed sized container where we can write a block of data at once. Channel
is a quite faster than stream-based I/O.
To read data from a file using Channel
we need to have the following steps-
- We need an instance of
FileInputStream
.FileInputStream
has a method namedgetChannel()
which returns a Channel. - Call the
getChannel()
method of FileInputStream and acquire Channel. - Create a ByteBuffer. ByteBuffer is a fixed size container of bytes.
- Channel has a read method and we have to provide a ByteBuffer as an argument to this read method. ByteBuffer has two modes - read-only mood and write-only mood. We can change the mode using
flip()
method call. Buffer has a position, limit, and capacity. Once a buffer is created with a fixed size, its limit and capacity are the same as the size and the position starts from zero. While a buffer is written with data, its position gradually increases. Changing mode means, changing the position. To read data from the beginning of a buffer, we have to set the position to zero. flip() method change the position - When we call the read method of the
Channel
, it fills up the buffer using data. - If we need to read the data from the
ByteBuffer
, we need to flip the buffer to change its mode to write-only to read-only mode and then keep reading data from the buffer. - When there is no longer data to read, the
read()
method of channel returns 0 or -1.
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChannelRead { public static void main(String[] args) { File inputFile = new File("hello.txt"); if (!inputFile.exists()) { System.out.println("The input file doesn't exit."); return; } try { FileInputStream fis = new FileInputStream(inputFile); FileChannel fileChannel = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (fileChannel.read(buffer) > 0) { buffer.flip(); while (buffer.hasRemaining()) { byte b = buffer.get(); System.out.print((char) b); } buffer.clear(); } fileChannel.close(); } catch (IOException e) { e.printStackTrace(); } } }
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents