Java FileChannel to Read a File

In this quick tutorial, we’ll look at how to use Java FileChannel to Read a File.  FileChannel class is available in the Java NIO library.

Read File with FileChannel


FileChannel performs faster than standard I/O when we read a large file. There are several benefits of using FileChannel as listed below –

  • Allows Reading and writing a file at a specific position.
  • It allows loading a section of a file directly into memory, which can be more efficient.
  • It allows the transfer of file data from one channel to another at a faster rate.
  • With FileChannel, a section of a file can be locked to restrict access by other threads.

Please note that although part of Java NIOFileChannel operations are blocking and do not have a non-blocking mode.

Below java code shows example of how to read file using FileChannel –

package com.kodehelp.javanio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by https://kodehelp.com
 */
public class FileChannelExample {
    public static void main(String args[]) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("/testfile.txt");
            FileChannel fileChannel = fis.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            int bytes = fileChannel.read(byteBuffer);
            while (bytes != -1) {
                byteBuffer.flip();
                while (byteBuffer.hasRemaining()) {
                    System.out.print((char) byteBuffer.get());
                }
                byteBuffer.clear();
                bytes = fileChannel.read(byteBuffer);
            }
            if (fis != null) {
                fis.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}