Reading a file using Channel and Buffer

suggest change

Channel 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-

  1. We need an instance of FileInputStream. FileInputStream has a method named getChannel() which returns a Channel.
  2. Call the getChannel() method of FileInputStream and acquire Channel.
  3. Create a ByteBuffer. ByteBuffer is a fixed-size container of bytes.
  4. 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.
  5. When we call the read method of the Channel, it fills up the buffer using data.
  6. 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.
  7. 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();
  }
 }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents