BufferedOutputStream是缓冲输出流,继承于FilterOutputStream,作用是为另外一个输出流提供换从功能。

主要函数列表:
BufferedOutputStream(OutputStream out)
BufferedOutputStream(OutputStream out, int size)
synchronized void close()
synchronized void flush()
synchronized void write(byte[] buffer, int offset, int length)
synchronized void write(int oneByte)

示例代码:

public class BufferedOutputStreamTest {

    private static final int LEN = 5;
    // 对应英文字母“abcddefghijklmnopqrsttuvwxyz”
    private static final byte[] ArrayLetters = {
        0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
        0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
    };

    public static void main(String[] args) {
        testBufferedOutputStream() ;
    }

    /**
     * BufferedOutputStream的API测试函数
    */
    private static void testBufferedOutputStream() {

        // 创建“文件输出流”对应的BufferedOutputStream
        // 它对应缓冲区的大小是16,即缓冲区的数据>=16时,会自动将缓冲区的内容写入到输出流。
        try {
            File file = new File("out.txt");
            OutputStream out =new BufferedOutputStream(new FileOutputStream(file), 16);
            // 将ArrayLetters数组的前10个字节写入到输出流中
            out.write(ArrayLetters, 0, 20);
            // 将“换行符\n”写入到输出流中
            out.write('\n');

            // TODO!
            out.flush();

            out.close();
            } catch (FileNotFoundException e) {
            e.printStackTrace();
            } catch (SecurityException e) {
            e.printStackTrace();
            } catch (IOException e) {
            e.printStackTrace();
            }
    }
}
运行结果是文件里有20个字符:abcdefghijklmnopqrst,由于这边设置的缓冲区大小是16,当输入的是20个字符时超过了16,不再使用缓冲区,直接将数据写入

基于JDK8的BufferedOutputStream类的源码:

public class BufferedOutputStream extends FilterOutputStream {
    /**
     * The internal buffer where data is stored.
     */
    //字符数组
    protected byte buf[];

    /**
     * The number of valid bytes in the buffer. This value is always
     * in the range <tt>0</tt> through <tt>buf.length</tt>; elements
     * <tt>buf[0]</tt> through <tt>buf[count-1]</tt> contain valid
     * byte data.
     */
    //字符数组中有效的字节
    protected int count;

    /**
     * Creates a new buffered output stream to write data to the
     * specified underlying output stream.
     *
     * @param   out   the underlying output stream.
     */
    //构造函数,字节数组大小是8*1024
    public BufferedOutputStream(OutputStream out) {
        this(out, 8192);
    }

    /**
     * Creates a new buffered output stream to write data to the
     * specified underlying output stream with the specified buffer
     * size.
     *
     * @param   out    the underlying output stream.
     * @param   size   the buffer size.
     * @exception IllegalArgumentException if size <= 0.
     */
    public BufferedOutputStream(OutputStream out, int size) {
        super(out);
        if (size <= 0) {
            throw new IllegalArgumentException("Buffer size <= 0");
        }
        buf = new byte[size];
    }

    /** Flush the internal buffer */
    //让缓冲数据进行写
    private void flushBuffer() throws IOException {
        if (count > 0) {
            out.write(buf, 0, count);
            count = 0;
        }
    }

    /**
     * Writes the specified byte to this buffered output stream.
     *
     * @param      b   the byte to be written.
     * @exception  IOException  if an I/O error occurs.
     */
    //写一个字节
    public synchronized void write(int b) throws IOException {
        if (count >= buf.length) {
            flushBuffer();
        }
        buf[count++] = (byte)b;
    }

    /**
     * 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.
     */
    //从b中off位置开始写len个字节
    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;
    }

    /**
     * Flushes this buffered output stream. This forces any buffered
     * output bytes to be written out to the underlying output stream.
     *
     * @exception  IOException  if an I/O error occurs.
     * @see        java.io.FilterOutputStream#out
     */
    //将缓冲数据写完
    public synchronized void flush() throws IOException {
        flushBuffer();
        out.flush();
    }
}

Java-IO之BufferedOutputStream(缓冲输出流)的更多相关文章

  1. java io系列13之 BufferedOutputStream(缓冲输出流)的认知、源码和示例

    本章内容包括3个部分:BufferedOutputStream介绍,BufferedOutputStream源码,以及BufferedOutputStream使用示例. 转载请注明出处:http:// ...

  2. java - >IO流_缓冲流(高效流)

    缓冲流(高效流) 在我们学习字节流与字符流的时候,大家都进行过读取文件中数据的操作,读取数据量大的文件时,读取的速度会很慢,很影响我们程序的效率,那么,我想提高速度,怎么办? Java中提高了一套缓冲 ...

  3. Java Io 流(输入输出流)

    IO流,也就是输入和输出流,可分为字节流和字符流. 1. 字节流 (1). InputStream 输入流,用于读取文件 输入流常用API: inputStream.read()  读取一个字节 in ...

  4. Java IO总结之缓冲读入文件

    package com.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException ...

  5. Java Io(数据输入输出流)

    Java Io 字节流中的DataInputStream 和 DataOutputStream,使用流更加方便,是流的一个扩展,更方便读取int, long,字符等类型数据. 事例代码如下: pack ...

  6. java IO流 之 字节输出流 OutputString()

    Java学习重点之一:OutputStream 字节输出流的使用 FileOutPutStream:子类,写出数据的通道 步骤: 1.获取目标文件 2.创建通道(如果原来没有目标文件,则会自动创建一个 ...

  7. 系统学习 Java IO (一)----输入流和输出流 InputStream/OutputStream

    目录:系统学习 Java IO ---- 目录,概览 InputStream 是Java IO API中所有输入流的父类. 表示有序的字节流,换句话说,可以将 InputStream 中的数据作为有序 ...

  8. Java IO流之缓冲流

    一.缓冲流简介 二.BufferedInputStream 三.其他三种缓冲流

  9. JAVA Io 缓冲输入输出流

    java中提供带缓冲的输入输出流.在打开文件进行写入或读取操作时,都会加上缓冲,提高了IO读写性能. 1. BufferedInputStream 缓冲输入流 2. BufferedOutputStr ...

  10. Java:输入输出流 java.io包的层次结构

    1.什么是IO Java中I/O操作主要是指使用Java进行输入,输出操作. Java所有的I/O机制都是基于数据流进行输入输出,这些数据流表示了字符或者字节数据的流动序列.Java的I/O流提供了读 ...

随机推荐

  1. ThreadLocal基本原理及运用

    ThreadLocal提供本地线程变量.这个变量里面的值(通过get方法获取)是和其他线程分割开来的,变量的值只有当前线程能访问到,不像一般的类型比如Person,Student类型的变量,只要访问到 ...

  2. numpy.random中的shuffle和permutation以及mini-batch调整数据集(X, Y)

    0. numpy.random中的shuffle和permutation numpy.random.shuffle(x) and numpy.random.permutation(x),这两个有什么不 ...

  3. Python Selenium 之数据驱动测试

    数据驱动模式的测试好处相比普通模式的测试就显而易见了吧!使用数据驱动的模式,可以根据业务分解测试数据,只需定义变量,使用外部或者自定义的数据使其参数化,从而避免了使用之前测试脚本中固定的数据.可以将测 ...

  4. MongoDB 索引限制

    额外开销 每个索引占据一定的存储空间,在进行插入,更新和删除操作时也需要对索引进行操作.所以,如果你很少对集合进行读取操作,建议不使用索引. 内存(RAM)使用 由于索引是存储在内存(RAM)中,你应 ...

  5. 使用Docker搭建GitLab

    使用docker-compose快速启动GitLab.(当然前提是你先安装docker-compose,安装方式见博客:http://blog.csdn.net/yulei_qq/article/de ...

  6. 开机小脚本自动打开sublime text 和git-bash

    set subl="C:\Program Files (x86)\Sublime Text 3\subl.exe" set git-bash="C:\Program Fi ...

  7. for循环创建文件夹

    bash里面, for n in a b c; do mkdir $n/dir; done 这个会在a,b,c三个文件夹下创建一个名为dir的文件夹. 之前没有在语句后面加分号,导致在cmd界面提交不 ...

  8. jboss规则引擎KIE Drools 6.3.0 Final 教程(3)

    在前2部教程中,介绍了如何在本地运行.drools文件以及使用stateless的方法访问远程repository上的规则. KIE Drools还提供了一种叫有状态-stateful的访问方式. 运 ...

  9. Linux 性能监测:IO

    磁盘通常是计算机最慢的子系统,也是最容易出现性能瓶颈的地方,因为磁盘离 CPU 距离最远而且 CPU 访问磁盘要涉及到机械操作,比如转轴.寻轨等.访问硬盘和访问内存之间的速度差别是以数量级来计算的,就 ...

  10. 20160212.CCPP体系详解(0022天)

    程序片段(01):01.二维数组.c 内容概要:二维数组 #include <stdio.h> #include <stdlib.h> //01.关于栈内存开辟数组: // 诀 ...