Java Program to read data from File using NIO.
Objective
Write a Java program to read data from a file using Java NIO Channels.
Algorithm / Approach
- Ask the user for the name of the file to read.
- Open a
FileInputStreamand extract itsReadableByteChannel. - Allocate a fixed-size
ByteBuffer(e.g., 1024 bytes). - Use a
do-whileloop to read chunks of data from the channel into the buffer:count = chan.read(buff). - If bytes were read, call
buff.rewind(), loop through the buffer, cast each byte to achar, and print it. - Continue looping until
read()returns -1 (End of File).
ReadFile.java
import java.io.*;
import java.nio.*;
import java.util.*;
import java.nio.channels.*;
class ReadFile {
public static void main(String[] a)
{
FileInputStream fis = null;
int count = 0;
ReadableByteChannel chan =null;
Scanner s=new Scanner(System.in);
System.out.print("Enter File: ");
String file = s.nextLine();
ByteBuffer buff = null;
try{
fis=new FileInputStream(file);
chan = fis.getChannel();
buff = ByteBuffer.allocate(1024);
do {
count = chan.read(buff);
if(count != -1) {
buff.rewind();
for(int i=0; i < count; i++)
System.out.print((char)buff.get());
}
} while(count != -1);
}
catch(Exception e) {
System.out.print(e);
}
finally {
try {
fis.close();
chan.close();
}
catch(Exception e) {
System.out.print(e);
}
}
}
}
Expected Output
Enter File: Alok.txt Java Prowess is one of the largest application for java
Explanation of the Program
- Reading with NIO is the exact reverse of writing.
- We use a loop because we don't know how large the file is. The 1024-byte Buffer acts as a bucket. We scoop up to 1024 bytes from the file channel, process them, and then scoop the next batch.
- The method
chan.read()returns the number of bytes successfully scooped. Once the file is empty, it returns-1, signaling us to stop the loop and close our resources in thefinallyblock.
Complexity
Time Complexity
O(n) - Where n is the number of bytes in the file.
Space Complexity
O(1) - Constant buffer size (1024 bytes) regardless of file size.