NIO Read File Java Example

Learn how to use the Java NIO APIs to read a file from the file system using buffer, channel, and path classes. In this article, we will learn about NIO Read File Java Example.

1. FileChannel and ByteBuffer for reading small files

Use this technique to read a small file where all of the contents of the file can fit in the buffer and the file can be read in one operation.

Example 1: Java reads a small file with ByteBuffer and RandomAccessFile

package com.handyopinion.test.nio;
 
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
 
public class ReadFileWithFileSizeBuffer
{
    public static void main(String args[])
    {
        try
        {
            RandomAccessFile aFile = new RandomAccessFile("test.txt","r");
 
            FileChannel inChannel = aFile.getChannel();
            long fileSize = inChannel.size();
 
            ByteBuffer buffer = ByteBuffer.allocate((int) fileSize);
            inChannel.read(buffer);
            buffer.flip();
 
            //Verify the file content
            for (int i = 0; i < fileSize; i++)
            {
                System.out.print((char) buffer.get());
            }
 
            inChannel.close();
            aFile.close();
        } 
        catch (IOException exc)
        {
            System.out.println(exc);
            System.exit(1);
        }
    }
}

2. FileChannel and ByteBuffer for reading large files

Use this technique to read a large file where all of the contents of the file cannot fit in the buffer at one time. The size of the buffer is required by a very large number. In this case, we can read the file in blocks with a small, fixed-size buffer.

Example 2: Java reads a large piece of file with a fixed size buffer

package com.handyopinion.test.nio;
 
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
 
public class ReadFileWithFixedSizeBuffer 
{
    public static void main(String[] args) throws IOException 
    {
        RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
 
        FileChannel inChannel = aFile.getChannel();
 
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while(inChannel.read(buffer) > 0)
        {
            buffer.flip();
            for (int i = 0; i < buffer.limit(); i++)
            {
                System.out.print((char) buffer.get());
            }
            buffer.clear(); // do something with the data and clear/compact it.
        }
 
        inChannel.close();
        aFile.close();
    }
}

3. Read a file with MappedByteBuffer

MappedByteBuffer extends the ByteBuffer class by operations that are specific to memory-mapped file areas.

Example 3: Reading a file with memory-mapped files in Java

package com.handyopinion.test.nio;
 
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
 
public class ReadFileWithMappedByteBuffer 
{
    public static void main(String[] args) throws IOException 
    {
        RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
 
        FileChannel inChannel = aFile.getChannel();
        MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
 
        buffer.load();  
        for (int i = 0; i < buffer.limit(); i++)
        {
            System.out.print((char) buffer.get());
        }
        buffer.clear(); // do something with the data and clear/compact it.
 
        inChannel.close();
        aFile.close();
    }
}

All of the above techniques read the contents of the file and output them to the console. In this article, we will learn about NIO Read File Java Example.

Next Articles

1. try-with-resources in Java 7
2. Java diamond operator – <> operator in Java

Please share this post:
Posts created 46

Ask a Question

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: