java nio 使用 gatheringbytechannel 接口的 write(bytebuffer[] srcs) 方法实现聚集写入。只需将多个 bytebuffer 对象放入数组并传入该方法,nio 通道会按顺序依次将每个缓冲区中剩余的数据写入底层目标(如文件或 socket),无需手动循环处理。

write() 在文件通道中的实际行为是什么
当使用 FileChannel 时,聚集写入会将所有缓冲区的字节连续追加到文件中。如果某个缓冲区为空或位置等于限制,该缓冲区会被跳过,不会报错,但总写入字节数是各缓冲区有效字节之和。

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GatheringWriteDemo {
public static void main(String[] args) throws IOException {
Path path = Paths.get("test.txt");
// 打开文件通道,支持写入和创建
try (FileChannel channel = FileChannel.open(path,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING)) {
ByteBuffer buffer1 = ByteBuffer.wrap(new byte[]{65, 66, 67}); // "ABC"
ByteBuffer buffer2 = ByteBuffer.wrap(new byte[]{100, 101}); // "de"
ByteBuffer buffer3 = ByteBuffer.allocate(0); // 空缓冲区
ByteBuffer[] buffers = {buffer1, buffer2, buffer3};
// 执行聚集写入
int bytesWritten = channel.write(buffers);
System.out.println("Total bytes written: " + bytesWritten);
// 预期输出: Total bytes written: 5
}
}
}
聚集写入与 Socket 通道的交互有何不同
在使用 SocketChannel 进行聚集写入时,行为与文件通道类似,但更受网络状态影响。如果网络缓冲区满导致部分写入,write() 返回实际写入的字节数,且所有缓冲区的 position 都会相应更新。这意味着下一次调用时,只有未写完的缓冲区及其后的缓冲区会被继续处理,已写完的缓冲区会被自动跳过。
Biome 是一个基于 Rust 的高性能工具链,适用于 JavaScript、TypeScript、JSX、JSON、CSS 和 GraphQL,它将格式化和 linting 统一到一个工具中。具有 97% 的 Prettier 兼容性以及超过 450 条 lint 规则,Biome 以显著更快的执行速度取代了 ESLint 和 Prettier。
立即学习“Java免费学习笔记(深入)”;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class SocketGatheringWriteDemo {
public static void main(String[] args) throws IOException {
// 注意:实际运行需确保本地有监听服务,此处仅展示逻辑结构
try (SocketChannel channel = SocketChannel.open(
new InetSocketAddress("localhost", 8080))) {
ByteBuffer header = ByteBuffer.wrap(new byte[]{0x01, 0x02});
ByteBuffer payload = ByteBuffer.wrap(new byte[]{0x03, 0x04, 0x05, 0x06});
ByteBuffer[] buffers = {header, payload};
// 尝试写入
int count = channel.write(buffers);
// 检查是否全部写入
if (count < (header.remaining() + payload.remaining())) {
System.out.println("Partial write occurred.");
// 此时 header.position 可能已移动,payload.position 也可能已移动
// 需要重新计算剩余数据或调整缓冲区位置
}
}
}
}
如果缓冲区中有未清理的标记(mark)会发生什么
聚集写入过程中,write() 方法只操作缓冲区的 position 和 limit,完全忽略 mark。如果某个缓冲区设置了 mark,写入后 mark 保持不变,但 position 已前进。这可能导致后续对该缓冲区的 reset() 操作指向错误的位置,或者在重复写入时产生意外行为。因此,在多次使用同一组缓冲区进行聚集写入前,建议重置缓冲区状态。

















