简体   繁体   中英

Piping output from an output stream to an input stream

My problem is piping input from one socket to another. Currently, I am using this code:

                    for(;;)
                    {
                        try
                        {
                            output2.write(input1.read());
                        }
                        catch(Exception err)
                        {
                            err.printStackTrace();
                        }
                    }

Even though this technically works, is there a faster way to do this?

You can use ByteStreams#copy(InputStream, OutputStream) from Google Guava:

try {
    ByteStreams.copy(input1, output2);
} catch (IOException x) {
    x.printStackTrace();
}

Without using any external libraries and without knowing any more than you have an OutputStream and an InputStream, you can use something like this.

byte[] buf = new byte[ 1024 ];
int read = 0;
while( ( read = in.read( buf ) ) != -1 ) {
    out.write( buf, 0, read );
}

This gives you the benefits of block moves, instead of single byte moves as in the code you posted.

This can be improved if we had more information on the types of IO streams you are using. You could look at Java.NIO which can provide much quicker block moves in the case of files or sockets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM