我了解BufferedOutputStream
背后的理论。将字节写入缓冲区数组直到其满,然后将其写入(丢弃)到基础流中-想法是它比逐字节写入要快,因为有更少的OS调用。
但是,从查看BufferedOutputStream
类和方法(BufferedOutputStream.java)的实现来看,似乎最终来自缓冲区的字节只是逐字节写入的。
我认为是这种情况,因为:
在BufferedOutputStream.write(byte b [],int off,int len)中,它的行是out.write(b,off,len)。由于out是OutputStream的实例,而不是BufferedOutputStream的实例,因此它正在调用OutputStream.write(byte [],int,int)。依次使用for循环逐字节写入
请有人能澄清一下实际发生的情况以及它的运行速度如何吗?
最佳答案
刷新数据后,将其作为一个块。
79 /** Flush the internal buffer */
80 private void flushBuffer() throws IOException {
81 if (count > 0) {
82 out.write(buf, 0, count);
83 count = 0;
84 }
85 }
FileOutputStream和许多其他重写OutputStream.write()以有效地处理数据块。
http://www.docjar.com/html/api/java/io/FileOutputStream.java.html
284
285 /**
286 * Writes a sub array as a sequence of bytes.
287 * @param b the data to be written
288 * @param off the start offset in the data
289 * @param len the number of bytes that are written
290 * @param append {@code true} to first advance the position to the
291 * end of file
292 * @exception IOException If an I/O error has occurred.
293 */
294 private native void writeBytes(byte b[], int off, int len, boolean append)
295 throws IOException;
308 /**
309 * Writes <code>len</code> bytes from the specified byte array
310 * starting at offset <code>off</code> to this file output stream.
311 *
312 * @param b the data.
313 * @param off the start offset in the data.
314 * @param len the number of bytes to write.
315 * @exception IOException if an I/O error occurs.
316 */
317 public void write(byte b[], int off, int len) throws IOException {
318 writeBytes(b, off, len, append);
319 }
关于java - BufferedOutputStream实际上如何在低级别工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9282909/