Most efficient way to create InputStream from OutputStream

前端 未结 5 591
-上瘾入骨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 03:01

    A simple solution that avoids copying the buffer is to create a special-purpose ByteArrayOutputStream:

    public class CopyStream extends ByteArrayOutputStream {
        public CopyStream(int size) { super(size); }
    
        /**
         * Get an input stream based on the contents of this output stream.
         * Do not use the output stream after calling this method.
         * @return an {@link InputStream}
         */
        public InputStream toInputStream() {
            return new ByteArrayInputStream(this.buf, 0, this.count);
        }
    }
    

    Write to the above output stream as needed, then call toInputStream to obtain an input stream over the underlying buffer. Consider the output stream as closed after that point.

提交回复
热议问题