zoukankan      html  css  js  c++  java
  • java io系列13之 BufferedOutputStream(缓冲输出流)的认知、源码和示例


    本章内容包括3个部分:BufferedOutputStream介绍,BufferedOutputStream源码,以及BufferedOutputStream使用示例。

    转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_13.html

    BufferedOutputStream 介绍

    BufferedOutputStream 是缓冲输出流。它继承于FilterOutputStream。
    BufferedOutputStream 的作用是为另一个输出流提供“缓冲功能”。

    BufferedOutputStream 函数列表

    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)

    BufferedOutputStream 源码分析(基于jdk1.7.40) 

     1 package java.io;
     2 
     3 public class BufferedOutputStream extends FilterOutputStream {
     4     // 保存“缓冲输出流”数据的字节数组
     5     protected byte buf[];
     6 
     7     // 缓冲中数据的大小
     8     protected int count;
     9 
    10     // 构造函数:新建字节数组大小为8192的“缓冲输出流”
    11     public BufferedOutputStream(OutputStream out) {
    12         this(out, 8192);
    13     }
    14 
    15     // 构造函数:新建字节数组大小为size的“缓冲输出流”
    16     public BufferedOutputStream(OutputStream out, int size) {
    17         super(out);
    18         if (size <= 0) {
    19             throw new IllegalArgumentException("Buffer size <= 0");
    20         }
    21         buf = new byte[size];
    22     }
    23 
    24     // 将缓冲数据都写入到输出流中
    25     private void flushBuffer() throws IOException {
    26         if (count > 0) {
    27             out.write(buf, 0, count);
    28             count = 0;
    29         }
    30     }
    31 
    32     // 将“数据b(转换成字节类型)”写入到输出流中
    33     public synchronized void write(int b) throws IOException {
    34         // 若缓冲已满,则先将缓冲数据写入到输出流中。
    35         if (count >= buf.length) {
    36             flushBuffer();
    37         }
    38         // 将“数据b”写入到缓冲中
    39         buf[count++] = (byte)b;
    40     }
    41 
    42     public synchronized void write(byte b[], int off, int len) throws IOException {
    43         // 若“写入长度”大于“缓冲区大小”,则先将缓冲中的数据写入到输出流,然后直接将数组b写入到输出流中
    44         if (len >= buf.length) {
    45             flushBuffer();
    46             out.write(b, off, len);
    47             return;
    48         }
    49         // 若“剩余的缓冲空间 不足以 存储即将写入的数据”,则先将缓冲中的数据写入到输出流中
    50         if (len > buf.length - count) {
    51             flushBuffer();
    52         }
    53         System.arraycopy(b, off, buf, count, len);
    54         count += len;
    55     }
    56 
    57     // 将“缓冲数据”写入到输出流中
    58     public synchronized void flush() throws IOException {
    59         flushBuffer();
    60         out.flush();
    61     }
    62 }

    说明
    BufferedOutputStream的源码非常简单,这里就BufferedOutputStream的思想进行简单说明:BufferedOutputStream通过字节数组来缓冲数据,当缓冲区满或者用户调用flush()函数时,它就会将缓冲区的数据写入到输出流中。

     

    示例代码

    关于BufferedOutputStream中API的详细用法,参考示例代码(BufferedOutputStreamTest.java)

     1 import java.io.BufferedOutputStream;
     2 import java.io.File;
     3 import java.io.OutputStream;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.io.FileNotFoundException;
     7 import java.lang.SecurityException;
     8 import java.util.Scanner;
     9 
    10 /**
    11  * BufferedOutputStream 测试程序
    12  *
    13  * @author skywang
    14  */
    15 public class BufferedOutputStreamTest {
    16 
    17     private static final int LEN = 5;
    18     // 对应英文字母“abcddefghijklmnopqrsttuvwxyz”
    19     private static final byte[] ArrayLetters = {
    20         0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
    21         0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
    22     };
    23 
    24     public static void main(String[] args) {
    25         testBufferedOutputStream() ;
    26     }
    27 
    28     /**
    29      * BufferedOutputStream的API测试函数
    30      */
    31     private static void testBufferedOutputStream() {
    32 
    33         // 创建“文件输出流”对应的BufferedOutputStream
    34         // 它对应缓冲区的大小是16,即缓冲区的数据>=16时,会自动将缓冲区的内容写入到输出流。
    35         try {
    36             File file = new File("out.txt");
    37             OutputStream out =
    38                   new BufferedOutputStream(
    39                       new FileOutputStream(file), 16);
    40 
    41             // 将ArrayLetters数组的前10个字节写入到输出流中
    42             out.write(ArrayLetters, 0, 10);
    43             // 将“换行符
    ”写入到输出流中
    44             out.write('
    ');
    45 
    46             // TODO!
    47             //out.flush();
    48 
    49             readUserInput() ;
    50 
    51             out.close();
    52        } catch (FileNotFoundException e) {
    53            e.printStackTrace();
    54        } catch (SecurityException e) {
    55            e.printStackTrace();
    56        } catch (IOException e) {
    57            e.printStackTrace();
    58        }
    59     }
    60 
    61     /**
    62      * 读取用户输入
    63      */
    64     private static void readUserInput() {
    65         System.out.println("please input a text:");
    66         Scanner reader=new Scanner(System.in);
    67         // 等待一个输入
    68         String str = reader.next();
    69         System.out.printf("the input is : %s
    ", str);
    70     }
    71 }

    运行结果
    生成文件“out.txt”,文件的内容是“abcdefghij”。
    分步测试:
    分别按照下面3种步骤测试程序,来查看缓冲区大小以及flush()的作用。

    第1种:原始程序。

    (01) 运行程序。在程序等待用户输入时,查看“out.txt”的文本内容;发现:内容为空。
    (02) 运行程序。在用户输入之后,查看“out.txt”的文本内容;发现:内容为“abcdefghij”。
    从中,我们发现(01)和(02)的结果不同;之所以(01)中的out.txt内容为空,是因为out.txt对应的缓冲区大小是16字节,而我们只写入了11个字节,所以,它不会执行清空缓冲操作(即,将缓冲数据写入到输出流中)。
    而(02)对应out.txt的内容是“abcdefghij”,是因为执行了out.close(),它会关闭输出流;在关闭输出流之前,会将缓冲区的数据写入到输出流中。
    注意:重新测试时,要先删除out.txt。

    第2种:在readUserInput()前添加如下语句,

    out.flush();

    这句话的作用,是将“缓冲区的内容”写入到输出流中。
    (01) 运行程序。在程序等待用户输入时,查看“out.txt”的文本内容;发现:内容为“abcdefghij”。
    (02) 运行程序。在用户输入之后,查看“out.txt”的文本内容;发现:内容为“abcdefghij”。
    从中,我们发现(01)和(02)结果一样,对应out.txt的内容都是“abcdefghij”。这是因为执行了flush()操作,它的作用是将缓冲区的数据写入到输出流中。
    注意:重新测试时,要先删除out.txt!


    第3种:在第1种的基础上,将

    out.write(ArrayLetters, 0, 10);

    修改为

    out.write(ArrayLetters, 0, 20);

    (01) 运行程序。在程序等待用户输入时,查看“out.txt”的文本内容;发现:内容为“abcdefghijklmnopqrst”(不含回车)。
    (02) 运行程序。在用户输入之后,查看“out.txt”的文本内容;发现:内容为“abcdefghijklmnopqrst”(含回车)。
    从中,我们发现(01)运行结果是“abcdefghijklmnopqrst”(不含回车)。这是因为,缓冲区的大小是16,而我们通过out.write(ArrayLetters, 0, 20)写入了20个字节,超过了缓冲区的大小;这时,会直接将全部的输入都写入都输出流中,而不经过缓冲区。
    (02)运行结果是“abcdefghijklmnopqrst”(含回车),这是因为执行out.close()时,将回车符号' '写入了输出流中。
    注意:重新测试时,要先删除out.txt!

    更多内容

    01. java 集合系列目录(Category)

    02. java io系列01之 IO框架

    03. java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括InputStream)

    04. java io系列03之 ByteArrayOutputStream的简介,源码分析和示例(包括OutputStream)

    05. java io系列04之 管道(PipedOutputStream和PipedInputStream)的简介,源码分析和示例

    06. java io系列05之 ObjectInputStream 和 ObjectOutputStream

    07. java io系列06之 序列化总结(Serializable 和 Externalizable)

    08. java io系列07之 FileInputStream和FileOutputStream

    09. java io系列08之 File总结

    10. java io系列09之 FileDescriptor总结

    11. java io系列10之 FilterInputStream

    12. java io系列11之 FilterOutputStream

    13. java io系列12之 BufferedInputStream(缓冲输入流)的认知、源码和示例

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

  • 相关阅读:
    struts2基础
    hibernate框架基础
    Django的模板层
    HBuilder无法连接夜神模拟器的解决办法
    Django的视图层
    Django的路由层
    Django简介
    http协议
    web应用
    Mongodb之增删改查
  • 原文地址:https://www.cnblogs.com/skywang12345/p/io_13.html
Copyright © 2011-2022 走看看