Most efficient way to create InputStream from OutputStream

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

    I think the best way to connect InputStream to an OutputStream is through piped streams - available in java.io package, as follow:

    // 1- Define stream buffer
    private static final int PIPE_BUFFER = 2048;
    
    // 2 -Create PipedInputStream with the buffer
    public PipedInputStream inPipe = new PipedInputStream(PIPE_BUFFER);
    
    // 3 -Create PipedOutputStream and bound it to the PipedInputStream object
    public PipedOutputStream outPipe = new PipedOutputStream(inPipe);
    
    // 4- PipedOutputStream is an OutputStream, So you can write data to it
    // in any way suitable to your data. for example:
    while (Condition) {
         outPipe.write(mByte);
    }
    
    /*Congratulations:D. Step 4 will write data to the PipedOutputStream
    which is bound to the PipedInputStream so after filling the buffer
    this data is available in the inPipe Object. Start reading it to
    clear the buffer to be filled again by the PipedInputStream object.*/
    

    In my opinion there are two main advantages for this code:

    1 - There is no additional consumption of memory except for the buffer.

    2 - You don't need to handle data queuing manually

提交回复
热议问题