标签:临时文件 java close code 发送 临时 test reader system
在Java语言中提供了各种各样的输入/输出流 Stream ,使我们能够很方便地对数据进行操作,其中管道流是一种特殊的流,用于在不同线程间直接传送数据。一个线程发送数据到输出管道流,另一个线程从输入管道流中读取数据。
通过使用管道,实现不同线程间的通信,而无须借助于类似临时文件之类的东西。
PipedInputStream 和 PipedOutputStream
PipedReader 和 PipedWriter
public class PipeStreamTest { public static void main(String[] args) throws IOException, InterruptedException { WriteData writeData = new WriteData(); ReadData readData = new ReadData(); PipedReader reader = new PipedReader(); PipedWriter writer = new PipedWriter(); writer.connect(reader); new Thread(() -> { writeData.writeMethod(writer); }).start(); Thread.sleep(2000); new Thread(() -> { readData.readMethod(reader); }).start(); } static class WriteData { public void writeMethod(PipedWriter writer) { try { System.out.println("write :"); for (int i = 0; i < 300; i++) { String outData = "" + (i + 1); writer.write(outData); System.out.print(outData); } System.out.println(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } static class ReadData { public void readMethod(PipedReader reader) { try { System.out.println("read :"); char[] byteArray = new char[20]; int readLength = reader.read(byteArray); while (readLength != -1) { String newData = new String(byteArray, 0, readLength); System.out.print(newData); readLength = reader.read(byteArray); } System.out.println(); reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
运行结果如下:
标签:临时文件 java close code 发送 临时 test reader system
原文地址:https://www.cnblogs.com/lkc9/p/12528466.html