首页 > Java > java教程 > Java中如何将OutputStream转换为InputStream?

Java中如何将OutputStream转换为InputStream?

Linda Hamilton
发布: 2024-11-09 04:11:02
原创
198 人浏览过

How to Convert an OutputStream to an InputStream in Java?

如何将 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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板