美文网首页
2021-09-21 IO流(管道流)

2021-09-21 IO流(管道流)

作者: Denholm | 来源:发表于2021-10-14 20:06 被阅读0次

    管道流

    PipedInputStream和PipedOutputStream
    输入输出可以直接进行连接,通过结合线程使用


    clipboard.png

    管道流涉及到多线程
    集合中涉及到流的是Properties(该类继承自Hashtable)

    import java.io.PipedInputStream;
    
    public class Read implements Runnable {
    
        private PipedInputStream in;
    
        public Read(PipedInputStream in) {
            this.in = in;
        }
    
        @Override
        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 (Exception e) {
                throw new RuntimeException("管道流读取失败!");
            }
        }
    
    }
    
    import java.io.PipedOutputStream;
    
    public class Write implements Runnable {
    
        private PipedOutputStream out;
    
        public Write(PipedOutputStream out) {
            this.out = out;
        }
    
        @Override
        public void run() {
            try {
                out.write("管道来啦".getBytes());
                out.close();
            } catch (Exception e) {
                throw new RuntimeException("管道流写入失败!");
            }
        }
    
    }
    
    import java.io.PipedInputStream;
    import java.io.PipedOutputStream;
    
    public class PipedStreamDemo {
    
        public static void main(String[] args) throws Exception {
            PipedInputStream pis = new PipedInputStream();
            PipedOutputStream pos = new PipedOutputStream();
            pis.connect(pos);
    //        pos.connect(pis);
    
            Read read = new Read(pis);
            Write write = new Write(pos);
    
            new Thread(read).start();
            new Thread(write).start();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:2021-09-21 IO流(管道流)

          本文链接:https://www.haomeiwen.com/subject/jlsbgltx.html