如何将 OutputStream 转换为 InputStream
在软件开发中,经常会遇到需要将数据从一个流转换为一个流的情况。流类型到另一个。其中一种场景是将 OutputStream 转换为 InputStream。
管道流简介
这个问题的解决方案在于使用 Java 的 PipedInputStream 和 PipedOutputStream 类。这些类通过创建双向管道来实现流之间的通信。
PipedInputStream 到 OutputStream(反之亦然)
Lambda 表达式:
PipedInputStream in = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(in); // in a background thread, write the given output stream to the PipedOutputStream for consumption new Thread(() -> { originalOutputStream.writeTo(out); }).start();
注意: 必须处理 OutputStream 可能过早关闭的情况,从而导致 ClosedPipeException。为了避免这种情况,您可以反转构造函数:
PipedInputStream in = new PipedInputStream(out); new Thread(() -> { originalOutputStream.writeTo(out); }).start();
Try-With-Resources:
// take the copy of the stream and re-write it to an InputStream PipedInputStream in = new PipedInputStream(); new Thread(new Runnable() { public void run() { // try-with-resources here // putting the try block outside the Thread will cause the PipedOutputStream resource to close before the Runnable finishes try (final PipedOutputStream out = new PipedOutputStream(in)) { // write the original OutputStream to the PipedOutputStream // note that in order for the below method to work, you need to ensure that the data has finished writing to the ByteArrayOutputStream originalByteArrayOutputStream.writeTo(out); } catch (IOException e) { // logging and exception handling should go here } } }).start();
PipedOutputStream 到 InputStream
如果您没有 ByteArrayOutputStream,可以使用以下代码:
PipedInputStream in = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(in); new Thread(new Runnable() { public void run() { try { // write the original OutputStream to the PipedOutputStream // note that in order for the below method to work, you need to ensure that the data has finished writing to the OutputStream originalOutputStream.writeTo(out); } catch (IOException e) { // logging and exception handling should go here } finally { // close the PipedOutputStream here because we're done writing data // once this thread has completed its run if (out != null) { // close the PipedOutputStream cleanly out.close(); } } } }).start();
使用管道流有几个好处,包括:
以上是Java中如何将OutputStream转换为InputStream?的详细内容。更多信息请关注PHP中文网其他相关文章!