从 OutputStream 创建 InputStream 的最有效方法 [英] Most efficient way to create InputStream from OutputStream

查看:31
本文介绍了从 OutputStream 创建 InputStream 的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本页:http://blog.ostermiller.org/convert-java-outputstream-输入流描述如何从 OutputStream 创建 InputStream:

This page: http://blog.ostermiller.org/convert-java-outputstream-inputstream describes how to create an InputStream from OutputStream:

new ByteArrayInputStream(out.toByteArray())

其他替代方案是使用 PipedStreams 和新线程,这很麻烦.

Other alternatives are to use PipedStreams and new threads which is cumbersome.

我不喜欢将许多兆字节复制到新的内存字节数组的想法.有没有可以更有效地执行此操作的库?

I do not like the idea of copying many megabytes to new in memory byte array. Is there a library that does this more efficiently?

根据 Laurence Gonsalves 的建议,我尝试了 PipedStreams,结果证明它们并不难处理.这是 clojure 中的示例代码:

By advice from Laurence Gonsalves, i tried PipedStreams and it turned out they are not that hard to deal with. Here's the sample code in clojure:

(defn #^PipedInputStream create-pdf-stream [pdf-info]
  (let [in-stream (new PipedInputStream)
        out-stream (PipedOutputStream. in-stream)]
    (.start (Thread. #(;Here you write into out-stream)))
    in-stream))

推荐答案

如果您不想一次将所有数据复制到内存缓冲区中,那么您将不得不让您的代码使用 OutputStream(生产者)和使用 InputStream(消费者)的代码要么在同一线程中交替使用,要么在两个单独的线程中同时运行.让它们在同一个线程中运行可能比使用两个单独的线程复杂得多,更容易出错(您需要确保使用者永远阻塞等待输入,否则您将有效地死锁)并且需要让生产者和消费者在同一个循环中运行,这似乎太紧密耦合了.

If you don't want to copy all of the data into an in-memory buffer all at once then you're going to have to have your code that uses the OutputStream (the producer) and the code that uses the InputStream (the consumer) either alternate in the same thread, or operate concurrently in two separate threads. Having them operate in the same thread is probably much more complicated that using two separate threads, is much more error prone (you'll need to make sure that the consumer never blocks waiting for input, or you'll effectively deadlock) and would necessitate having the producer and consumer running in the same loop which seems way too tightly coupled.

所以使用第二个线程.真的没有那么复杂.您链接到的页面有合理的示例.这是一个有点现代化的版本,它也关闭了流:

So use a second thread. It really isn't that complicated. The page you linked to had reasonable example. Here's a somewhat modernized version, which also closes the streams:

try (PipedInputStream in = new PipedInputStream()) {
    new Thread(() -> {
        try (PipedOutputStream out = new PipedOutputStream(in)) {
            writeDataToOutputStream(out);
        } catch (IOException iox) {
            // handle IOExceptions
        }
    }).start();
    processDataFromInputStream(in);
}

这篇关于从 OutputStream 创建 InputStream 的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆