import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.hiviewdfx.HiLogConst;
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
public class PipedWriterExample {
private static final HiLogLabel LABEL = new HiLogLabel(HiLogConst.DEBUG, 0x00201, "PipedWriterExample");
public static void main(String[] args) {
try {
// 创建PipedReader和PipedWriter
PipedReader pipedReader = new PipedReader();
PipedWriter pipedWriter = new PipedWriter();
// 将字符输入流和字符输出流关联起来
pipedReader.connect(pipedWriter);
// 创建一个线程,用于写入字符数据到输出流
Thread writerThread = new Thread(() -> {
try {
// 向输出流写入字符数据
String dataToWrite = "Hello, HarmonyOS!";
pipedWriter.write(dataToWrite);
pipedWriter.close(); // 关闭输出流
} catch (IOException e) {
HiLog.error(LABEL, "写入数据时发生错误:{}", e.getMessage());
}
});
// 启动线程
writerThread.start();
// 从输入流读取字符数据
char[] buffer = new char[1024];
int charsRead = pipedReader.read(buffer);
String dataRead = new String(buffer, 0, charsRead);
HiLog.info(LABEL, "从管道中读取到的数据:{}", dataRead);
// 等待线程结束
writerThread.join();
} catch (IOException | InterruptedException e) {
HiLog.error(LABEL, "发生错误:{}", e.getMessage());
}
}
}
在这个例子中,创建了一个PipedWriter和一个PipedReader,并通过connect()方法将它们关联起来。然后,创建了一个线程,该线程负责向PipedWriter写入字符数据。主线程从关联的PipedReader中读取字符数据。请注意,PipedWriter的write方法和close方法可能会抛出IOException,因此在实际应用中需要适当处理异常。
转载请注明出处:http://www.zyzy.cn/article/detail/3053/鸿蒙OS