Most efficient way to create InputStream from OutputStream

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

    I usually try to avoid creating a separate thread because of the increased chance of deadlock, the increased difficulty of understanding the code, and the problems of dealing with exceptions.

    Here's my proposed solution: a ProducerInputStream that creates content in chunks by repeated calls to produceChunk():

    public abstract class ProducerInputStream extends InputStream {
    
        private ByteArrayInputStream bin = new ByteArrayInputStream(new byte[0]);
        private ByteArrayOutputStream bout = new ByteArrayOutputStream();
    
        @Override
        public int read() throws IOException {
            int result = bin.read();
            while ((result == -1) && newChunk()) {
                result = bin.read();
            }
            return result;
        }
    
        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            int result = bin.read(b, off, len);
            while ((result == -1) && newChunk()) {
                result = bin.read(b, off, len);
            }
            return result;
        }
    
        private boolean newChunk() {
            bout.reset();
            produceChunk(bout);
            bin = new ByteArrayInputStream(bout.toByteArray());
            return (bout.size() > 0);
        }
    
        public abstract void produceChunk(OutputStream out);
    
    }
    

提交回复
热议问题