1
\$\begingroup\$

I'm writing a method to save an input stream to an output stream. What's the optimal size for the buffer? Here's my method:

/**
* Saves the given InputStream to a file at the destination. Does not check whether the destination exists.
*
* @param inputStream
* @param destination
* @throws FileNotFoundException
* @throws IOException
*/
public static void saveInputStream(InputStream inputStream, File outputFile) throws FileNotFoundException, IOException {
 try (OutputStream out = new FileOutputStream(outputFile)) {
 byte[] buffer = new byte[2097152]; //This is set to two MB. But I have no idea whether this is optimal
 int length;
 while ((length = inputStream.read(buffer)) > 0) {
 out.write(buffer, 0, length);
 }
 inputStream.close();
 }
}
asked May 7, 2012 at 14:09
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

It depends on a lot of factors, there's no universally "optimal" size. 512kB is probably good enough.

If you want, you can always benchmark it for various buffer sizes: this will let you know what the best option is for your computer and OS.

answered May 7, 2012 at 14:26
\$\endgroup\$
2
  • \$\begingroup\$ Just asked a question about getting the block size. Could be useful. But I think you're right :) \$\endgroup\$ Commented May 7, 2012 at 16:04
  • \$\begingroup\$ You still should benchmark it. You'll be surprised by the results! \$\endgroup\$ Commented May 7, 2012 at 16:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.