File Channel Example
This program demonstrates reading a file using NIO channels.
Problem Statement
Write a Java program that reads data from a file using FileChannel.
Source Code
| 1 | import java.io.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | public class FileChannelExample { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq File Channel Example"); |
| 7 | try(FileInputStream fis=new FileInputStream("sample.txt"); |
| 8 | FileChannel channel=fis.getChannel()) { |
| 9 | ByteBuffer buffer=ByteBuffer.allocate(64); |
| 10 | while(channel.read(buffer)>0){ |
| 11 | buffer.flip(); |
| 12 | while(buffer.hasRemaining()){ |
| 13 | System.out.print((char)buffer.get()); |
| 14 | } |
| 15 | buffer.clear(); |
| 16 | } |
| 17 | } catch(IOException e) { |
| 18 | System.out.println("\nEduinq Exception: "+e.getMessage()); |
| 19 | } |
| 20 | } |
| 21 | } |
Program Output
Eduinq File Channel Example Hello Eduinq Welcome to File Handling
Explanation
File channels provide faster I/O using buffers. - Reads data into ByteBuffer. - Exception handling ensures safe operations. - In enterprise systems, channels are used for high-performance file access. Conclusion: Shows reading files using NIO channels.