\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
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
-
\$\begingroup\$ Just asked a question about getting the block size. Could be useful. But I think you're right :) \$\endgroup\$kentcdodds– kentcdodds2012年05月07日 16:04:26 +00:00Commented May 7, 2012 at 16:04
-
\$\begingroup\$ You still should benchmark it. You'll be surprised by the results! \$\endgroup\$Quentin Pradet– Quentin Pradet2012年05月07日 16:13:37 +00:00Commented May 7, 2012 at 16:13
lang-java