ScatteringByteChannel
从多个通道读取 − 在此中,我们制作了将数据从单个通道读取到多个缓冲区中。为此,将分配多个缓冲区并将其添加到缓冲区类型数组中。然后,将此数组作为参数传递给散射字节通道 read() 方法,该方法然后按照缓冲区在数组中出现的顺序从通道写入数据。缓冲区已满后,通道将继续填充下一个缓冲区。
以下示例显示了如何在 Java NIO 中执行数据分散
C:/Test/temp.txt
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ScatteringByteChannel;
public class ScatterExample {
private static String FILENAME = "C:/Test/temp.txt";
public static void main(String[] args) {
ByteBuffer bLen1 = ByteBuffer.allocate(1024);
ByteBuffer bLen2 = ByteBuffer.allocate(1024);
FileInputStream in;
try {
in = new FileInputStream(FILENAME);
ScatteringByteChannel scatter = in.getChannel();
scatter.read(new ByteBuffer[] {bLen1, bLen2});
bLen1.position(0);
bLen2.position(0);
int len1 = bLen1.asIntBuffer().get();
int len2 = bLen2.asIntBuffer().get();
System.out.println("Scattering : Len1 = " + len1);
System.out.println("Scattering : Len2 = " + len2);
}
catch (FileNotFoundException exObj) {
exObj.printStackTrace();
}
catch (IOException ioObj) {
ioObj.printStackTrace();
}
}
}