Most efficient way to create InputStream from OutputStream

前端 未结 5 584
-上瘾入骨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:53

    There is another Open Source library called EasyStream that deals with pipes and thread in a transparent way. That isn't really complicated if everything goes well. Problems arise when (looking at Laurence Gonsalves example)

    class1.putDataOnOutputStream(out);

    Throws an exception. In that example the thread simply completes and the exception is lost, while the outer InputStream might be truncated.

    Easystream deals with exception propagation and other nasty problems I've been debugging for about one year. (I'm the mantainer of the library: obviously my solution is the best one ;) ) Here is an example on how to use it:

    final InputStreamFromOutputStream isos = new InputStreamFromOutputStream(){
     @Override
     public String produce(final OutputStream dataSink) throws Exception {
       /*
        * call your application function who produces the data here
        * WARNING: we're in another thread here, so this method shouldn't 
        * write any class field or make assumptions on the state of the outer class. 
        */
       return produceMydata(dataSink)
     }
    };
    

    There is also a nice introduction where all other ways to convert an OutputStream into an InputStream are explained. Worth to have a look.

提交回复
热议问题