FileChannel Scatter/Gather Example

This program demonstrates scatter/gather I/O using FileChannel.

Problem Statement

Write a Java program that reads data into multiple buffers (scatter) and writes from multiple buffers (gather) using FileChannel.

Source Code

1 import java.io.*;
2 import java.nio.*;
3 import java.nio.channels.*;
4 public class ScatterGatherExample {
5 public static void main(String[] args) {
6 System.out.println("Eduinq Scatter/Gather Example");
7 try(RandomAccessFile raf=new RandomAccessFile("sample.txt","rw");
8 FileChannel fc=raf.getChannel()) {
9 ByteBuffer header=ByteBuffer.allocate(10);
10 ByteBuffer body=ByteBuffer.allocate(50);
11 ByteBuffer[] buffers={header,body};
12 fc.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 } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); }
17 }
18 }

Program Output

					Eduinq Scatter/Gather Example
Eduinq Header: (first 10 chars)
Eduinq Body: (next 50 chars)
				

Explanation

Scatter reads into multiple buffers. - Gather writes from multiple buffers. - Exception handling ensures safe operations. - In enterprise systems, scatter/gather supports structured data. Conclusion: Shows scatter/gather I/O with FileChannel.

Quick Links to Explore