zoukankan      html  css  js  c++  java
  • Java I/O流-PipedInputStream、PipedOutputStream

    一、整体代码图

           PipedStreamDemo.java

    import java.io.*;
    
    class PipedStreamDemo            
    {
      public static void main(String[] args)  throws Exception
      {
        PipedInputStream pin = new PipedInputStream();
        PipedOutputStream pout = new PipedOutputStream();
        pin.connect(pout);  //输入流与输出流连接
        
        ReadThread readTh   = new ReadThread(pin);
        WriteThread writeTh = new WriteThread(pout);
        new Thread(readTh).start();
        new Thread(writeTh).start();
      }
      
      public static void sop(Object obj) //打印
      {
        System.out.println(obj);
      }
    }
    
    class ReadThread implements Runnable
    {
      private PipedInputStream pin;
      ReadThread(PipedInputStream pin)   //
      {
        this.pin=pin;
      }
      
      public void run() //由于必须要覆盖run方法,所以这里不能抛,只能try
      {
        try
        {
          sop("R:读取前没有数据,阻塞中...等待数据传过来再输出到控制台...");
          byte[] buf = new byte[1024];
          int len = pin.read(buf);  //read阻塞
          sop("R:读取数据成功,阻塞解除...");
          
          String s= new String(buf,0,len);
          sop(s);    //将读取的数据流用字符串以字符串打印出来
          pin.close();     
        }
        catch(Exception e)
        {
          throw new RuntimeException("R:管道读取流失败!");
        }   
      }
      
      public static void sop(Object obj) //打印
      {
        System.out.println(obj);
      }
    }
    
    class WriteThread implements Runnable
    {
      private PipedOutputStream pout;
      WriteThread(PipedOutputStream pout)
      {
        this.pout=  pout;
      }
      
      public void run()
      {
        try
        {
          sop("W:开始将数据写入:但等个5秒让我们观察...");
          Thread.sleep(5000);  //释放cpu执行权5秒
          pout.write("W: writePiped 数据...".getBytes());  //管道输出流
          pout.close();
        }
        catch(Exception e)
        {
          throw new RuntimeException("W:WriteThread写入失败...");
        }
      }
      
      public static void sop(Object obj) //打印
      {
        System.out.println(obj);
      }
    }
    
    
    
    

      

    二、解释

            

  • 相关阅读:
    Android:Unable to find explicit activity class报错
    家庭记账本2
    家庭记账本开发
    Android Studio中TableLayout(表格布局)
    Android Studio中View与ViewGroup的概念
    Android Studio反编译APK获取代码&资源
    Android程序签名打包
    Android Studio工程相关解析(各种文件,资源访问)
    Android Studio 的SDK更新不了问题解决
    模块
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3297337.html
Copyright © 2011-2022 走看看