java - BufferedOutputStream 实际上是如何在底层工作的?

标签 java buffer flush bufferedoutputstream

我了解BufferedOutputStream 背后的理论。字节被写入缓冲区数组,直到它已满,然后写入(刷新)到底层流 - 这个想法比逐字节写入更快,因为操作系统调用更少。

但是,从 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循环逐字节写入

请有人澄清实际发生了什么,以及它如何更快?

最佳答案

当数据被刷新时,它是一个 block 。

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() 以有效地处理数据 block 。

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/

相关文章:

java - 按字母顺序对 Java 对象排序为 JSON 对象

opengl-es - glMapBuffer 在 OpenGL-ES 2.0 中未声明

emacs - 如何设置 Emacs gdb 以便在箭头上显示最近的命令?

java - 写入android Audio Tack的缓冲区后,音频文件播放晚

c - 如何在 Linux 中使用 ioctl(原始分区)正确刷新磁盘缓存

c - 正常虚拟程序后标准输入未刷新

c++ - 简单来说,ostream中flush()的作用是什么

Java Web 应用程序国际化 : Where should I store big texts?

java - 无法附加到 HDFS

java - 每个扩展类的静态变量