Reading a file using Channel and Buffer
suggest changeChannel uses a Buffer to read/write data. A buffer is a fixed-size container where we can write a block of data at once. Channel is quite a bit 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.FileInputStreamhas 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. A buffer is filled by writing at its position, then
flip()prepares it for reading: it sets the limit to the current position and the position to zero. 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. - 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, which switches it from writing to reading, 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 exist.");
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