java源码-BufferedWriter

开篇

 BufferedWriter和BufferedReader是对称的,一并分析下源码。


源码分析

构造函数

  • BufferedWriter的构造函数通过缓冲区char cb[]数组保存待持久化字符
  • 缓存区默认大小为8192
  • BufferedWriter跟BufferedReader一样采用装饰者模式进行设计,通过内部Writer out对象保存被装饰的Writer对象。
  • BufferedWriter的写操作通过被装饰的out对象进行数据写入。
public class BufferedWriter extends Writer {

    private Writer out;

    private char cb[];
    private int nChars, nextChar;
    private static int defaultCharBufferSize = 8192;
    private String lineSeparator;

    public BufferedWriter(Writer out) {
        this(out, defaultCharBufferSize);
    }

    public BufferedWriter(Writer out, int sz) {
        super(out);
        if (sz <= 0)
            throw new IllegalArgumentException("Buffer size <= 0");
        this.out = out;
        cb = new char[sz];
        nChars = sz;
        nextChar = 0;

        lineSeparator = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("line.separator"));
    }



write过程

  • write过程先把数据写到缓冲区cb数组当中
  • 当缓冲区cb数组当中的字符超出最大缓存区大小,那么就执行flush保存数据
    public void write(int c) throws IOException {
        synchronized (lock) {
            ensureOpen();
            // 超出缓存区大小就执行flush操作
            if (nextChar >= nChars)
                flushBuffer();
            cb[nextChar++] = (char) c;
        }
    }

    void flushBuffer() throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (nextChar == 0)
                return;
            // 将数据通过out对象进行持久化
            out.write(cb, 0, nextChar);
            // 重置缓冲区的起始位置
            nextChar = 0;
        }
    }
    }


类依赖图

  • BufferedWriter的类依赖图如下图,所有的io writer都是继承自Writer作为基类。
java源码-BufferedWriter_第1张图片

你可能感兴趣的:(java源码-BufferedWriter)