PipedReader
类和PipedWriter
类是管道字符流。管道用于将输出从一个程序(或线程)发送到另一个程序(或线程)的输入。
以下是使用PipedReader
和PipedWriter
的示例。 在此示例中,一个线程将数据写入管道,另一个线程从该管道读取数据。
文件:PipedReaderWriterExample.java –
package com.yiibai.tutorial.io; import java.io.IOException; import java.io.PipedReader; import java.io.PipedWriter; /** * @author yiibai */ public class PipedReaderWriterExample { public static void main(String[] args) throws Exception { final PipedReader pipedReader = new PipedReader(); final PipedWriter pipedWriter = new PipedWriter(); // Connect pipe pipedReader.connect(pipedWriter); // Writing data to pipe Thread writerThread = new Thread(new Runnable() { @Override public void run() { try { for (int i = 65; i <= 70; i++) { pipedWriter.write((char) i); Thread.sleep(500); } pipedWriter.close(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }); // Reading data from pipe Thread readerThread = new Thread(new Runnable() { @Override public void run() { try { int i; while ((i = pipedReader.read()) != -1) { System.out.println((char) i); Thread.sleep(1000); } pipedReader.close(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }); // Start thread writerThread.start(); readerThread.start(); } }
上面示例代码,得到以下输出结果:
A B C D E F
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264101.html