声明 我看的是java7的API文档。
如下图所示,java.io.writer 继承了java.lang.Object,实现的接口有Closeable, Flushable, Appendable, AutoCloseable。
所有直接继承它的子类有BufferedWriter CharArrayWriter FilterWriter OutputStreamWriter PipedWriter PrintWriter StringWriter。
Writer是用来操作字符流的抽象类。所有继承它的子类必须要重写的方法有write(char[], int, int), flush(), and close().
下面是java.io.Writer的源码。
packagejava.io;public abstract class Writer implementsAppendable,Closebale,Flushable{private char[] writeBuffer;private static final int WRITE_BUFFER_SIZE = 1024;
projected Object lock;protectedWriter(){this.lock = this;
}protectedWriter(Object lock){if(lock == null){throw newNullPointerException();
}this.lock =lock;
}public void write(int c) throwIOException{
syschronized (lock){if (writeBuffer == null){
writeBuffer= new char[WRITE_BUFFER_SIZE];
}
writeBuffer[0] = (char) c;
write(writeBuffer,0,1);
}
}public void write(char cbuf[]) throwIOException{
write(cbuf,0, cbuf.length);
}abstract public void write(char buf[], int off, int len) throwIOException;public void write(String str) throwIOException{
write(str,0, str.length());
}public void write(String str, int off, int len) throwIOException{
syschronized(lock){charcbuf[];if(len <=WRITE_BUFFER_SIZE){if(writeBuffer == null){
writeBuffer= new char[WRITE_BUFFER_SIZE];
}
cbuf=writeBuffer;
}else{
cbuf= new char[len];
}
str.getChars(off, (off+ len), cbuf, 0);
write(cbuf,0,len);
}
}public Writer append(CharSequence csq) throwsIOException{if(csq == null)
write("null");elsewrite(csq.toString());return this;
}public Writer append(CharSequence csq, int start, int end) throwIOException{
CharSequence cs= (csq == null ? "null": csq);
write(cs.subSequence(start,end).toString());return this;
}public Writer append(char c) throwIOException{
write(c);return this;
}abstract public void flush() throwIOException;abstract public void close() throwIOException;
}
可以看到在Writer类中子类必须重写的类有三个,
1、abstract public void write(char buf[], int off, int len) throw IOException;
2、abstract public void flush() throw IOException;
3、abstract public void close() throw IOException;
其中,下面三个方法是实现Appendable接口必须实现的方法
1、public Writer append(CharSequence csq) throws IOException
2、public Writer append(CharSequence csq, int start, int end) throw IOException
3、public Writer append(char c) throw IOException
实现 Flushable接口必须实现的方法是
abstract public void flush() throw IOException;
实现Closeable接口必须实现的方法是
abstract public void close() throw IOException;