0
\$\begingroup\$

This is a simple function that copies the content of one stream to another. My question is simple. I am currently, copying between the streams one byte at a time, but the streams are both Buffered. What are some ways to optimize it for speed? Any other advice would be appreciated as well.

private boolean copyToStream(BufferedInputStream inputStream, BufferedOutputStream fileStream) throws IOException {
    int byt;
    while ((byt = inputStream.read()) != -1) {
        fileStream.write(byt);
        }
    }
    return true;

}
\$\endgroup\$
1
\$\begingroup\$

Instead of reading the buffered stream byte-by-byte inputStream.read() you might use the advantage of buffering. This will speed up the large content copy.

private boolean copyToStream(BufferedInputStream inputStream, BufferedOutputStream fileStream) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];
    int n;
    while ((n = inputStream.read(buffer)) != -1) {
        fileStream.write(buffer, 0, n);
    }
}

Also, consider java.nio.FileChannel transferTo() which may allow using DMA.

\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome? \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Oct 11 '18 at 21:31
  • \$\begingroup\$ Doesn't wrapping the streamed around buffered input and output already make my streams buffered though? \$\endgroup\$ – Gnik Oct 13 '18 at 2:32
  • \$\begingroup\$ @Gnik It does, and in the code provided its advantage is used by the bulk read/write. With a single char read/write the buffer can be not engaged at all. \$\endgroup\$ – Semyon Sadetsky Oct 15 '18 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.