← 中文资源

简体中文版本

Channels 桥接流与通道

用 java.nio.channels.Channels 把 InputStream/OutputStream 适配成通道,再通过共享 ByteBuffer 搬运字节并还原内容。

阅读英文原文

实现说明

Channels 桥接流与通道以类 ChannelsBridgeDemo为骨架。 循环只出现在 while (source.read(buffer) != -1),它的每次迭代处理一个元素。

使用要点

  • 每一步打印都带着自己的标签:copied bytes:、content:、captured:。

常见问题

运行「Channels 桥接流与通道」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 copied bytes:、content:、captured: 这类标签。

核心语句

total += target.write(buffer);

代码示例

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;

public class ChannelsBridgeDemo {
    public static void main(String[] args) throws Exception {
        byte[] payload = "channel bridge payload".getBytes(StandardCharsets.UTF_8);
        ByteArrayOutputStream sink = new ByteArrayOutputStream();

        // Channels.newChannel 把 InputStream 适配为可读通道
        ReadableByteChannel source = Channels.newChannel(new ByteArrayInputStream(payload));
        WritableByteChannel target = Channels.newChannel(sink);

        ByteBuffer buffer = ByteBuffer.allocate(8);
        int total = 0;
        while (source.read(buffer) != -1) {
            buffer.flip();
            total += target.write(buffer);
            buffer.clear();
        }
        source.close();
        target.close();

        System.out.println("copied bytes: " + total);
        System.out.println("content: " + sink.toString(StandardCharsets.UTF_8));

        // 反向桥接:通道写回 OutputStream 再转字节数组
        ByteArrayOutputStream captured = new ByteArrayOutputStream();
        WritableByteChannel writeChannel = Channels.newChannel(captured);
        writeChannel.write(ByteBuffer.wrap("done".getBytes(StandardCharsets.UTF_8)));
        writeChannel.close();
        System.out.println("captured: " + captured.toString(StandardCharsets.UTF_8));
    }
}