您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何将OutputStream转换为InputStream?

如何将OutputStream转换为InputStream?

nOutputStream是您向其中写入数据的地方。如果某个模块公开了OutputStream,则期望在另一端读取一些内容

InputStream另一方面,暴露出的信息表示您需要侦听此流,并且会有一些数据可以读取。

因此可以将一个连接InputStream一个OutputStream

InputStream----read---> intermediateBytes[n] ----write----> OutputStream

正如有人提到的那样,这就是IoUtils的copy()方法可以让您完成的工作。走另一条路是没有道理的…希望这是有道理的

更新:

当然,我对这一点的思考越多,我越能看到这实际上是一项要求。我知道一些提及Piped输入/输出流的评论,但是还有另一种可能性。

如果公开的输出流是ByteArrayOutputStream,那么您始终可以通过调用toByteArray()方法获取全部内容。然后,您可以使用ByteArrayInputStream子类创建输入流包装器。这两个都是伪流,它们基本上都只是包装一个字节数组。因此,以这种方式使用流在技术上是可行的,但对我来说仍然很奇怪…

似乎有很多链接和其他类似内容,但没有使用管道的实际代码。使用java.io.PipedInputStream和的优点java.io.PipedOutputStream是没有额外的内存消耗。ByteArrayOutputStream.toByteArray()返回原始缓冲区的副本,这意味着内存中的任何内容现在都有两个副本。然后写一个数据InputStream意味着您现在有了数据的三个副本。

编码:

// take the copy of the stream and re-write it to an InputStream
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
            // ByteArrayOutputStream
            originalByteArrayOutputStream.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();

这段代码假定originalByteArrayOutputStreama一个ByteArrayOutputStream因为它通常是唯一可用的输出流,除非您要写入文件。我希望这有帮助!这样做的好处在于,由于它在一个单独的线程中,因此也可以并行工作,因此,无论消耗您的输入流,还是从旧的输出流中流出。这是有益的,因为缓冲区可以保持较小,并且您将拥有更少的延迟和更少的内存使用量。

其他 2022/1/1 18:16:24 有497人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶