该类无继承类,完成了Appendable、Closeable、Flushable接口
该类无引入包
该类的类头注释如下:
/** * Abstract class for writing to character streams. The only methods that a * subclass must implement are write(char[], int, int), flush(), and close(). * Most subclasses, however, will override some of the methods defined here in * order to provide higher efficiency, additional functionality, or both. * * @see Writer * @see BufferedWriter * @see CharArrayWriter * @see FilterWriter * @see OutputStreamWriter * @see FileWriter * @see PipedWriter * @see PrintWriter * @see StringWriter * @see Reader * * @author Mark Reinhold * @since JDK1.1 */
大意如下:
该类是用于写出字符流的抽象类
该类的子类必须完成写出字符数组方法、刷新以及关闭流方法
然而大部分的子类都会覆写该类中声明的一些方法来提供更高的效率,或者添加一些新功能
该类含有如下的成员变量:
写出缓冲区
private char[] writeBuffer;
默认缓冲区大小
private static final int WRITE_BUFFER_SIZE = 1024;
控制同步锁
protected Object lock;
该类含有如下的成员方法:
默认构造方法:(仅绑定同步锁
protected Writer() { this.lock = this; }
构造方法(给予同步锁进行绑定
protected Writer(Object lock) { if (lock == null) { throw new NullPointerException(); } this.lock = lock; }
写入单个字符
public void write(int c) throws IOException { synchronized (lock) { if (writeBuffer == null){//如果缓冲区未初始化 writeBuffer = new char[WRITE_BUFFER_SIZE]; } writeBuffer[0] = (char) c; write(writeBuffer, 0, 1);//将缓冲区中数据写入流中 } }
向流中写入字符数组
public void write(char cbuf[]) throws IOException { write(cbuf, 0, cbuf.length); }
向流中写入字符数组区间
abstract public void write(char cbuf[], int off, int len) throws IOException;
向流中写入字符串
public void write(String str) throws IOException { write(str, 0, str.length()); }
向流中写入字符串区间
public void write(String str, int off, int len) throws IOException { synchronized (lock) {//线程同步 char cbuf[]; if (len <= WRITE_BUFFER_SIZE) {//判定需要写出的数据大小,如果比默认的大小大就不使用内部缓冲区,新建一个缓冲区 if (writeBuffer == null) { writeBuffer = new char[WRITE_BUFFER_SIZE]; } cbuf = writeBuffer; } else { // Don't permanently allocate very large buffers. cbuf = new char[len]; } str.getChars(off, (off + len), cbuf, 0); write(cbuf, 0, len); } }
向缓冲区中添加字符序列
public Writer append(CharSequence csq) throws IOException { if (csq == null) write("null"); else write(csq.toString()); return this; }
向缓冲区中添加字符序列部分段
public Writer append(CharSequence csq, int start, int end) throws IOException { CharSequence cs = (csq == null ? "null" : csq);//为空就写个空进去... write(cs.subSequence(start, end).toString()); return this; }
向缓冲区中添加单个字符
public Writer append(char c) throws IOException { write(c); return this; }
刷新流
abstract public void flush() throws IOException;
关闭流
abstract public void close() throws IOException;
该类由于目前是字符输出流的顶级类,在append方法和write方法方面看着差别不是很大,但在后续使用中推荐使用append方法与flush组合效率比较高。同时该类的构造函数和其他流顶级类的构造函数都有一个特点:都对自己本身进行同步控制,同步在IO中占有重要的地位,与数据的准确性和效率紧密联系。
如果需要看一些实例的话,推荐StringWriter、BufferWriter和FilterWriter类