user375868 user375868 - 5 months ago 67
Java Question

Better way of copying InputStream to OutputStream

Is there a better way of copying

InputStream
to
OutputStream
?

I have an input stream provided by, say,
HttpClient
. I have another stream which is connected to servlet output stream.

To copy data from input stream to output stream I am using apache
IOUtils.copy
method which uses a temporary buffer for copying.

I am wondering if I use
ByteBuffer
will it help performance wise?

EJP EJP
Answer Source

You can't get away without a buffer with streams, unless you want to copy a byte at a time, which isn't efficient unless you know there are buffered streams in the stack for both input and output.

You can't use ByteBuffers with streams. You can use them with channels, and you can get channels from streams, but all you're doing is adding extra layers over the streams API. You're better off confronting it direct, as below. In the case of network streams, the performance is dominated by the network, not by the code, in any case.

while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

Works for all sizes of buffer greater than zero. I usually use 8192.