FileChannel Read Example
This program demonstrates reading a file using FileChannel.
Problem Statement
Write a Java program that reads file content using FileChannel and ByteBuffer.
Source Code
| 1 | import java.io.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | import java.nio.file.*; |
| 5 | public class FileChannelReadExample { |
| 6 | public static void main(String[] args) throws Exception { |
| 7 | System.out.println("Eduinq FileChannel Read Example"); |
| 8 | FileChannel channel=FileChannel.open(Paths.get("sample.txt"),StandardOpenOption.READ); |
| 9 | ByteBuffer buffer=ByteBuffer.allocate(1024); |
| 10 | channel.read(buffer); |
| 11 | buffer.flip(); |
| 12 | while(buffer.hasRemaining()){ System.out.print((char)buffer.get()); } |
| 13 | channel.close(); |
| 14 | } |
| 15 | } |
Program Output
Eduinq FileChannel Read Example (sample.txt content displayed)
Explanation
Uses FileChannel.read() with ByteBuffer. - Efficiently reads file content. - Exception handling ensures safe operations. - In enterprise systems, FileChannel supports high performance I/O. Conclusion: Shows reading with FileChannel.