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

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

问题描述

此页: http://blog.ostermiller.org/convert-java-outputstream -inputstream
描述了如何从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?

编辑:

根据劳伦斯的建议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的代码(使用者) )要么在同一个线程中交替,要么在两个单独的线程中同时操作。让它们在同一个线程中运行可能要复杂得多,使用两个独立的线程,更容易出错(你需要确保消费者从不阻止等待输入,或者你' ll有效死锁)并且必须让生产者和消费者在相同的循环中运行,这似乎是太紧密耦合。

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 a perfect example:

  PipedInputStream in = new PipedInputStream();
  PipedOutputStream out = new PipedOutputStream(in);
  new Thread(
    new Runnable(){
      public void run(){
        class1.putDataOnOutputStream(out);
      }
    }
  ).start();
  class2.processDataFromInputStream(in);

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

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