- Java NIO 教程
- Java NIO - 首页
- Java NIO - 概述
- Java NIO - 环境设置
- Java NIO vs JAVA IO
- Java NIO - 通道(Channels)
- Java NIO - 文件通道(File Channel)
- Java NIO - 数据报通道(DataGram Channel)
- Java NIO - 套接字通道(Socket Channel)
- Java NIO - 服务器套接字通道(Server Socket Channel)
- Java NIO - 分散(Scatter)
- Java NIO - 收集(Gather)
- Java NIO - 缓冲区(Buffer)
- Java NIO - 选择器(Selector)
- Java NIO - 管道(Pipe)
- Java NIO - 路径(Path)
- Java NIO - 文件(File)
- Java NIO - 异步文件通道(AsynchronousFileChannel)
- Java NIO - 字符集(CharSet)
- Java NIO - 文件锁(FileLock)
- Java NIO 有用资源
- Java NIO - 快速指南
- Java NIO - 有用资源
- Java NIO - 讨论
Java NIO - 收集(Gather)
众所周知,与传统的 Java IO API 相比,Java NIO 是一个更优化的数据 IO 操作 API。Java NIO 提供的另一个额外支持是从多个缓冲区读取/写入数据到通道。这种多重读写支持被称为分散和收集,其中在读取数据时,数据从单个通道分散到多个缓冲区,而在写入数据时,数据从多个缓冲区收集到单个通道。
为了实现从通道进行这种多重读写,Java NIO 提供了 ScatteringByteChannel 和 GatheringByteChannel API 来读取和写入数据,如下例所示。
GatheringByteChannel(收集字节通道)
写入多个通道 - 在这里,我们将数据从多个缓冲区写入单个通道。为此,将分配多个缓冲区并将其添加到缓冲区类型数组中。然后,将此数组作为参数传递给 GatheringByteChannel write() 方法,该方法随后按缓冲区在数组中出现的顺序从多个缓冲区写入数据。这里需要注意的是,只有缓冲区位置和限制之间的数据才会被写入。
以下示例演示了如何在 Java NIO 中执行数据收集。
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
public class GatherExample {
private static String FILENAME = "C:/Test/temp.txt";
public static void main(String[] args) {
String stream1 = "Gather data stream first";
String stream2 = "Gather data stream second";
ByteBuffer bLen1 = ByteBuffer.allocate(1024);
ByteBuffer bLen2 = ByteBuffer.allocate(1024);
// Next two buffer hold the data we want to write
ByteBuffer bstream1 = ByteBuffer.wrap(stream1.getBytes());
ByteBuffer bstream2 = ByteBuffer.wrap(stream2.getBytes());
int len1 = stream1.length();
int len2 = stream2.length();
// Writing length(data) to the Buffer
bLen1.asIntBuffer().put(len1);
bLen2.asIntBuffer().put(len2);
System.out.println("Gathering : Len1 = " + len1);
System.out.println("Gathering : Len2 = " + len2);
// Write data to the file
try {
FileOutputStream out = new FileOutputStream(FILENAME);
GatheringByteChannel gather = out.getChannel();
gather.write(new ByteBuffer[] {bLen1, bLen2, bstream1, bstream2});
out.close();
gather.close();
}
catch (FileNotFoundException exObj) {
exObj.printStackTrace();
}
catch(IOException ioObj) {
ioObj.printStackTrace();
}
}
}
输出
Gathering : Len1 = 24 Gathering : Len2 = 25
最后,可以得出结论,在 Java NIO 中引入分散/收集方法是一种经过优化的多任务方法(如果使用得当)。它允许您将将读取的数据分成多个块的分离工作委托给操作系统,或将不同的数据块组合成一个整体。毫无疑问,这节省了时间,并通过避免缓冲区复制更有效地利用操作系统,并减少了需要编写和调试的代码量。
广告