Bridge Streams And Channels With Channels

Wrap InputStream and OutputStream as channels with java.nio.channels.Channels, then copy bytes through a shared ByteBuffer.

JavaData Fetching

Code

snippet
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));
    }
}

How it works

Bridge Streams And Channels With Channels is built around the class ChannelsBridgeDemo.

The cycling part of this snippet is while (source.read(buffer) != -1).

Putting it to use

The demo output is labeled (copied bytes:, content:, captured:), so the output doubles as a step-by-step trace of what the file did.

Core lines

total += target.write(buffer);

FAQ

What does Bridge Streams And Channels With Channels print when run?
The script runs standalone; its 3 labeled outputs include `copied bytes:`, `content:`, `captured:`.