Most efficient way to create InputStream from OutputStream

前端 未结 5 593
-上瘾入骨i
-上瘾入骨i 2020-11-28 02:25

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

new ByteArrayInputStr         


        
5条回答
  •  心在旅途
    2020-11-28 02:52

    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);
    

提交回复
热议问题