Java NIO : read small size file using FileChannel

Read the file Using ByteBuffer and file Size:

import java.io.IOException;
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 = FileChannel.open(file);
        
        //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.
        fileChannel.read(buffer);
        
        //Limit set to current position and the position set to 0
        buffer.flip();
        
        //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
        fileChannel.close();

    }
}

 

Advertisements


Categories: Java Programming

Tags:

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: