Java Programming

Java NIO : read small size file using FileChannel

Read the file Using ByteBuffer and file Size:

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ReadFileUsingFileChannel {

    public static void main(String args[]) throws IOException {
        String inputFile = "D:\\SampleFile.txt";
        //Set the Path with input file        
        Path file = Paths.get(inputFile);
        //Open the file
        FileChannel fileChannel =;
        //Get the Size of the file, Returns the current size of this channel's file.
        long fileSize = fileChannel.size();
        System.out.println("File Size in bytes::"+fileSize);
        //Allocate ByteBuffer Object with fileSize        
        ByteBuffer buffer = ByteBuffer.allocate((int) fileSize);
        //Reads the sequence of bytes from this channel into buffer.;
        //Limit set to current position and the position set to 0
        //Print the data on the console.
        System.out.println("File Data is :::");
        for (int i = 0; i < fileSize; i++) {
            System.out.print((char) buffer.get());

        //Close the File channel resource



Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.