首页 > 代码库 > PipedOutputStream&PipedInputStream---管道流

PipedOutputStream&PipedInputStream---管道流

管道流通常与多线程技术相结合

import java.io.IOException;import java.io.PipedInputStream;import java.io.PipedOutputStream;public class PipedStreamDemo {    public static void main(String[] args) throws IOException {                //管道流和多线程技术相结合        PipedInputStream pis =new PipedInputStream();        PipedOutputStream pos = new PipedOutputStream();                //将两个流连接上。        pis.connect(pos);        new Thread(new Input(pis)).start();        new Thread(new Output(pos)).start();            }}//定义输入任务class Input implements Runnable{        private PipedInputStream pis;        public Input(PipedInputStream pis) {        super();        this.pis = pis;    }    @Override    public void run() {                byte[] buf = new byte[1024];        int len;        try {            len = pis.read(buf);            String str = new String(buf,0,len);            System.out.println(str);            pis.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }            }}//定义输出任务class Output implements Runnable{    PipedOutputStream pos;            public Output(PipedOutputStream pos) {        super();        this.pos = pos;    }    @Override    public void run() {                //通过写方法完成        try {            pos.write("嘿,管道来了".getBytes());                        pos.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }            }        }

 

PipedOutputStream&PipedInputStream---管道流