Channel
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-
FileInputStream
. FileInputStream
has a method named getChannel()
which returns a Channel.getChannel()
method of FileInputStream and acquire Channel.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 positionChannel
, it fills up the buffer using data.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.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();
}
}
}