createpipe(java怎么用CreatePipe建立管道)

发布时间:2025-12-11 01:06:05 浏览次数:1

在Java中,可以使用PipedInputStreamPipedOutputStream类来创建管道。

以下是使用PipedInputStreamPipedOutputStream建立管道的示例代码:

import java.io.IOException;import java.io.PipedInputStream;import java.io.PipedOutputStream;public class PipeExample {    public static void main(String[] args) {        try {            // 创建管道输入流和输出流            PipedInputStream inputStream = new PipedInputStream();            PipedOutputStream outputStream = new PipedOutputStream();            // 将输入流和输出流连接起来            inputStream.connect(outputStream);            // 创建发送线程和接收线程            Thread senderThread = new Thread(() -> {                try {                    // 向输出流写入数据                    outputStream.write("Hello, World!".getBytes());                    outputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            });            Thread receiverThread = new Thread(() -> {                try {                    byte[] buffer = new byte[1024];                    int bytesRead = inputStream.read(buffer);                    System.out.println("Received: " + new String(buffer, 0, bytesRead));                    inputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            });            // 启动发送线程和接收线程            senderThread.start();            receiverThread.start();        } catch (IOException e) {            e.printStackTrace();        }    }}

当运行以上代码时,接收线程将从输入流中读取数据,并打印出来。输出结果应为Received: Hello, World!

createpipe
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477