如果将缓冲区大小调整为文件大小,则表示只要文件大小太大而无法使用可用内存,就会出现OutOfMemoryError。
使用正常的缓冲区大小让它做它的工作 - 以流式方式缓冲数据,一次缓冲一个块,而不是一次性缓冲。
有关说明,请参阅BufferedOutputStream的文档:
The class implements a buffered output stream. By setting up such an
output stream, an application can write bytes to the underlying output
stream without necessarily causing a call to the underlying system for
each byte written.
因此,使用缓冲区比非缓冲写入更有效。
并从write方法:
Ordinarily this method stores bytes from the given array into this
stream's buffer, flushing the buffer to the underlying output stream
as needed. If the requested length is at least as large as this
stream's buffer, however, then this method will flush the buffer and
write the bytes directly to the underlying output stream.
每次写入都会导致内存缓冲区填满,直到缓冲区已满。缓冲区已满时,将刷新并清除。如果使用非常大的缓冲区,则会在刷新之前将大量数据存储在内存中。如果您的缓冲区与输入文件的大小相同,那么您说在刷新之前需要将整个内容读入内存。使用默认缓冲区大小通常很好。将有更多的物理写入(刷新);你避免爆炸记忆。
通过允许您指定特定的缓冲区大小,API允许您在内存消耗和I / O之间选择适当的平衡以适合您的应用程序。如果您调整应用程序的性能,最终可能会调整缓冲区大小。但是在许多情况下,默认大小是合理的。