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.nio.ByteBuffer;
import java.nio.channels.FileChannel;

 * Created by
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 =;
            while (bytes != -1) {
                while (byteBuffer.hasRemaining()) {
                    System.out.print((char) byteBuffer.get());
                bytes =;
            if (fis != null) {
        } catch (FileNotFoundException e) {
        } catch (IOException e) {