FileChannel Position Example
This program demonstrates setting position in FileChannel.
Problem Statement
Write a Java program that sets position in FileChannel before reading.
Source Code
| 1 | import java.io.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | import java.nio.file.*; |
| 5 | public class FileChannelPositionExample { |
| 6 | public static void main(String[] args) throws Exception { |
| 7 | System.out.println("Eduinq FileChannel Position Example"); |
| 8 | FileChannel channel=FileChannel.open(Paths.get("sample.txt"),StandardOpenOption.READ); |
| 9 | channel.position(5); |
| 10 | ByteBuffer buffer=ByteBuffer.allocate(20); |
| 11 | channel.read(buffer); |
| 12 | buffer.flip(); |
| 13 | while(buffer.hasRemaining()){ System.out.print((char)buffer.get()); } |
| 14 | channel.close(); |
| 15 | } |
| 16 | } |
Program Output
Eduinq FileChannel Position Example (content from position 5 onwards)
Explanation
Uses channel.position() to set offset. - Reads from specified position. - Exception handling ensures safe operations. - In enterprise systems, position supports partial reads. Conclusion: Shows setting position in FileChannel.