Scatter Read Example
This program demonstrates scatter read using FileChannel.
Problem Statement
Write a Java program that reads data into multiple buffers using scatter read.
Source Code
| 1 | import java.io.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | import java.nio.file.*; |
| 5 | public class ScatterReadExample { |
| 6 | public static void main(String[] args) throws Exception { |
| 7 | System.out.println("Eduinq Scatter Read Example"); |
| 8 | FileChannel channel=FileChannel.open(Paths.get("scatter.txt"),StandardOpenOption.READ); |
| 9 | ByteBuffer header=ByteBuffer.allocate(10); |
| 10 | ByteBuffer body=ByteBuffer.allocate(50); |
| 11 | ByteBuffer[] buffers={header,body}; |
| 12 | channel.read(buffers); |
| 13 | header.flip(); body.flip(); |
| 14 | System.out.println("Eduinq Header: "+new String(header.array()).trim()); |
| 15 | System.out.println("Eduinq Body: "+new String(body.array()).trim()); |
| 16 | channel.close(); |
| 17 | } |
| 18 | } |
Program Output
Eduinq Scatter Read Example Eduinq Header: (first 10 chars) Eduinq Body: (next 50 chars)
Explanation
Uses scatter read to fill multiple buffers. - Splits data into header and body. - Exception handling ensures safe operations. - In enterprise systems, scatter read supports structured data. Conclusion: Shows scatter read with FileChannel.