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);

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.

  • \$\begingroup\$ Just asked a question about getting the block size. Could be useful. But I think you're right :) \$\endgroup\$ – kentcdodds May 7 '12 at 16:04
  • \$\begingroup\$ You still should benchmark it. You'll be surprised by the results! \$\endgroup\$ – Quentin Pradet May 7 '12 at 16:13

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.