JavaIO流学习总结-PipedReader和PipedWriter基本操作练习

Posted musong1998

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaIO流学习总结-PipedReader和PipedWriter基本操作练习相关的知识,希望对你有一定的参考价值。

package io;
import java.io.*;
/*
 * 修改日期:2020/04/05
 * 修改人:牟松
 * 管道流(字节流)PipedReader和PipedWriter基本操作练习
 * 参考链接:https://blog.csdn.net/sk199048/article/details/51260757
 */
class Producer extends Thread {
    private PipedWriter writer = new PipedWriter();
   
    public Producer(PipedWriter writer) {
        this.writer = writer;
    }
    @Override
    public void run() {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("Hello World!");
            writer.write(sb.toString());
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Consumer extends Thread{
    private PipedReader reader = new PipedReader();
    public Consumer(PipedReader reader) {
        this.reader = reader;
    }
    @Override
    public void run() {
        try {
            char [] cbuf = new char[20];
            reader.read(cbuf, 0, cbuf.length);       
            System.out.println("管道流中的数据为: " + new String(cbuf));
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public class ceshi {
   public static void main(String[] args)
     { 
     /**
      * 线程间通过管道流通信的步骤为
      * 1 建立输入输出流
      * 2 绑定输入输出流
      * 3 Writer写
      * 4 Reader读
      */
     PipedReader reader = new PipedReader();
     PipedWriter writer = new PipedWriter();
     Producer producer = new Producer(writer);
     Consumer consumer = new Consumer(reader);
     try {
         writer.connect(reader);
         producer.start();
         consumer.start();
     } catch (Exception e) {
         e.printStackTrace();
     }
     }
}

以上是关于JavaIO流学习总结-PipedReader和PipedWriter基本操作练习的主要内容,如果未能解决你的问题,请参考以下文章

JavaIO流学习总结-FileReader和FileWriter基本操作练习

JavaIo流总结

JavaIO学习总结一

JavaIO流学习总结-InputStreamReader和OutputStreamWriter基本操作练习

JavaIO流学习总结-ObjectOutputStream和ObjectInputStream基本操作练习

java io流