zoukankan      html  css  js  c++  java
  • Java基础之管道流对象 PipedInputStream / PipedOutputStream

    管道流 PipedInputStream / PiedOutputStream 说明:输入输出可以直接进行连接,通过结合线程使用。
    import java.io.*;

    class PipedStreamDemo
    {
        public static void main(String[] args) throws Exception
        {
            PipedInputStream in = new PipedInputStream();
            PipedOutputStream out = new PipedOutputStream();
            
            in.connect(out);
            
            new Thread(new Reader(in)).start();
            new Thread(new Writer(out)).start();
        }
    }

    class Reader implements Runnable
    {
        private PipedInputStream in;
        public Reader(PipedInputStream in)
        {
            this.in = in;
        }
        
        public void run()
        {
            try        
            {
                byte[] buffer = new byte[1024];
                int length = 0;
                System.out.println("等待读取数据...");
                while((length=in.read(buffer))!=-1)
                {
                    System.out.println(new String(buffer,0,length));
                }
                
                in.close();
            }
            catch(Exception e)
            {
                throw new RuntimeException(e.getMessage());
            }
        }
    }

    class Writer implements Runnable
    {
        private PipedOutputStream out;
        public Writer(PipedOutputStream out)
        {
            this.out = out;
        }
        
        public void run()
        {
            try        
            {
                System.out.println("六秒后开始写入数据...");
                Thread.sleep(6000);
                out.write("hello PipedStream here.".getBytes());
                out.close();
            }
            catch(Exception e)
            {
                throw new RuntimeException(e.getMessage());
            }
        }
    }
  • 相关阅读:
    .NET中使用Redis总结 —— 1.Redis搭建
    Java 通过JDBC连接Mysql数据库
    5.java设计模式之建造者模式
    4.java设计模式之原型模式
    3.java设计模式之工厂模式
    2.java设计模式之单例模式
    1.java设计模式之七大设计原则和UML类图
    1.使用javax.mail, spring的JavaMailSender,springboot发送邮件
    1.7 栈(使用数组模拟)
    1.6 单向环形链表和约瑟夫问题
  • 原文地址:https://www.cnblogs.com/cxmsky/p/2891434.html
Copyright © 2011-2022 走看看