您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在性能方面,在什么时候用BufferedOutputStream包裹FileOutputStream才有意义?

在性能方面,在什么时候用BufferedOutputStream包裹FileOutputStream才有意义?

当写入小于缓冲区大小(例如8 KB)时,bufferedoutputstream会提供帮助。对于较大的写入,它无济于事,也不会使其变得更糟。如果您的所有写操作都大于缓冲区大小,或者每次写操作后始终都使用flush(),则我不会使用缓冲区。但是,如果您的写入中有很大一部分小于缓冲区大小,并且您并非每次都使用flush(),那么值得这样做。

您可能会发现将缓冲区大小增加到32 KB或更大可以对您有所改善,或者使情况变得更糟。青年汽车

您可能会发现bufferedoutputstream.write的代码很有用

/**
 * Writes <code>len</code> bytes from the specified byte array
 * starting at offset <code>off</code> to this buffered output stream.
 *
 * <p> 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.  Thus redundant
 * <code>bufferedoutputstream</code>s will not copy data unnecessarily.
 *
 * @param      b     the data.
 * @param      off   the start offset in the data.
 * @param      len   the number of bytes to write.
 * @exception  IOException  if an I/O error occurs.
 */
public synchronized void write(byte b[], int off, int len) throws IOException {
    if (len >= buf.length) {
        /* If the request length exceeds the size of the output buffer,
           flush the output buffer and then write the data directly.
           In this way buffered streams will cascade harmlessly. */
        flushBuffer();
        out.write(b, off, len);
        return;
    }
    if (len > buf.length - count) {
        flushBuffer();
    }
    System.arraycopy(b, off, buf, count, len);
    count += len;
}
其他 2022/1/1 18:29:48 有618人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶