0

With the following logic used to copy a file using input/output streams. Is there truly a benefit of using the Bufferred Streams since it is using a byte buffer of the same size?

int bufferSize = getDefaultBufferSize();
input = new BufferedInputStream(in, bufferSize);
output = new BufferedOutputStream(out, bufferSize);
byte[] buffer = new byte[bufferSize];
int numBytes = 0;
long totalBytes = 0L;
while ((numBytes = input.read(buffer)) != -1) {
    output.write(buffer, 0, numBytes);
    totalBytes += numBytes;
}
output.flush();
2
  • Same size to what? What are you really comparing here? Whether you want to use in and out directly? Commented Apr 14, 2020 at 18:17
  • The size is the same for input stream/output stream/buffer. However I do not believe the streams are necessary and provide any performance increase because the array buffer is used when reading and writing anyway. Commented Apr 15, 2020 at 21:19

1 Answer 1

1

BufferedInputStream gives you no benefit at all here.

With BufferedOutputStream it's not so clear. The underlying output device may support efficient transfer of blocks that are larger than the blocks that the input stream returns, so removing BufferedOutputStream may mean you'll make a larger number of smaller writes.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for confirming what I thought. Wouldn't the BufferredOutputStream not have any benefit in this scenario as well? Since the array buffer is same size and we are writing using the buffer the underlying output device issue would apply with or without the usage of the BufferredOutputStream no?
Reading from the input stream, you'll get blocks of data in sizes determined by the input device. Let's say it's typically 1kB. Let's say bufferSize is 4kB. Without buffered output you'll write a 1kB block to the output device in every run of the loop. With buffered output, you'll write 4kB once every 4 runs. Whether that is a meaningful difference is hard to say

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.