Java管道流PipedStream

PiperInputStream

PiperOutputStream

输入输出可以直接连接,通过结合线程使用。

 

管道输入流应该连接到管道输出流;管道输入流提供要写入管道输出流的所有数据字节。

 

构造方法摘要

PipedInputStream()
创建尚未连接 PipedInputStream

 

PipedInputStream(PipedOutputStream src)
创建 PipedInputStream,使其连接到管道输出流 src

 

 

 

方法摘要

void

connect(PipedOutputStream src)
使此管道输入流连接到管道输出流 src

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PiperStreamDemo {
   public static void main(String[] args) throws IOException {
      PipedInputStream input = new PipedInputStream();
      PipedOutputStream output = new PipedOutputStream();
      input.connect(output);
      // 或者
      // PipedInputStream input=new PipedInputStream();
      // PipedOutputStream output=new PipedOutputStream(input);     // //或者
      // PipedOutputStream output=new PipedOutputStream(input);
      // PipedInputStream input=new PipedInputStream(output);
      new Thread(new Input(input)).start();
      try {
         Thread.sleep(5000);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
      new Thread(new Output(output)).start();
   }
}

class Input implements Runnable {
   private PipedInputStream in;

   public Input(PipedInputStream in) {
      super();
      this.in = in;
   }

   public void run() {
      try {
         byte buf[] = new byte[1024];
         int len = in.read(buf);
         String s = new String(buf, 0, len);
         System.out.println(s);
         in.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

class Output implements Runnable {
   private PipedOutputStream out;

   public Output(PipedOutputStream out) {
      super();
      this.out = out;
   }

   public void run() {
      try {
         out.write("hi,管道来了".getBytes());
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}