FileChannel Read Example

This program demonstrates reading a file using FileChannel.

Problem Statement

Write a Java program that reads data from a file using FileChannel and ByteBuffer.

Source Code

1 import java.io.*;
2 import java.nio.*;
3 import java.nio.channels.*;
4 public class FileChannelReadExample {
5 public static void main(String[] args) {
6 System.out.println("Eduinq FileChannel Read Example");
7 try(FileInputStream fis=new FileInputStream("sample.txt");
8 FileChannel fc=fis.getChannel()) {
9 ByteBuffer buffer=ByteBuffer.allocate(1024);
10 fc.read(buffer);
11 buffer.flip();
12 while(buffer.hasRemaining()){
13 System.out.print((char)buffer.get());
14 }
15 } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); }
16 }
17 }

Program Output

					Eduinq FileChannel Read Example
(sample.txt content displayed)
				

Explanation

Uses FileChannel with ByteBuffer. - Efficient reading with NIO. - Exception handling ensures safe operations. - In enterprise systems, FileChannel supports scalable I/O. Conclusion: Shows reading with FileChannel.

Quick Links to Explore