java io学习(十八) CharArrayWriter(字符数组输出流)2014-08-12
CharArrayWriter 介绍
CharArrayReader 用于写入数据符,它继承于Writer。操作的数据是以字符为单位!CharArrayWriter 函数列表
CharArrayWriter()CharArrayWriter(int initialSize) CharArrayWriter append(CharSequence csq, int start, int end)CharArrayWriter append(char c)CharArrayWriter append(CharSequence csq)void close()void flush()void reset()int size()char[] toCharArray()String toString()void write(char[] buffer, int offset, int len)void write(int oneChar)void write(String str, int offset, int count)void writeTo(Writer out)
Writer和CharArrayWriter源码分析Writer是CharArrayWriter的父类,我们先看看Writer的源码,然后再学CharArrayWriter的源码。1. Writer源码分析(基于jdk1.7.40)
package java.io; public abstract class Writer implements Appendable, Closeable, Flushable { private char[] writeBuffer; private final int writeBufferSize = 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[writeBufferSize];}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 <= writeBufferSize) {if (writeBuffer == null) {writeBuffer = new char[writeBufferSize];}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");elsewrite(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;}