How to use a FileChannel to read data into a Buffer in java code?

Below Java code shows how to use FileChannel to read data into buffer.

This is done by following below steps :

  • Create FileInputStream for the file to be read
  • Create FileChannel from FileInputStream
  • Create ByteBuffer as channel reads data into buffer and set the limit of ByteBuffer.
  • Read data from channel to byteBuffer
  • To read data from ByteBuffer we need to flip the byteBuffer from writing mode to reading mode. This can be done by calling byteBuffer.flip() method.
/****************************************************************************************
* Created on 09-2011Copyright(c) https://kodehelp.com All Rights Reserved.
****************************************************************************************/
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 Date: 9/22/11
 */
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();
        }
    }
}