简介
FilterWriter与FilterReader作为字符流中一种"过滤流",名称上与字节过滤流FilterInputStream和FilterOutputStream有些相似,但在继承关系上有点不一样.
1.FilterInputStream的常见子类有DataInputStream,PushBackInputStream,BufferedInputStream等,而FilterOutputStream常见的子类有DataOutputStream,BufferedOutputStream,PrintStream等,而字符流中过滤流,FilterReader的子类有PushBackReader.FilterWriter没有子类,与字节过滤流中继承关系差别较大,
2.FilterWriter,FilterReader作为抽象类,分别继承了父类Writer和Reader抽象类,除了简单覆盖父类方法,没有添加额外的方法.
3.由于FilterWriter没有子类,FilterReader只有子类PushBackReader,字符"过滤流"目前为止,没看到实际的用处.可以留作以后扩展使用.
FilterWriter源码
public abstract class FilterWriter extends Writer {
protected Writer out;
//有参构造方法,传入基础字符输出流
protected FilterWriter(Writer out) {
super(out);
this.out = out;
}
//将单个字符写到输出流中
public void write(int c) throws IOException {
out.write(c);
}
//将字符数组cbuf中off位置开始,len个字节写到输出流中
public void write(char cbuf[], int off, int len) throws IOException {
out.write(cbuf, off, len);
}
//将字符串中off位置开始,len个字符写到输出流中.
public void write(String str, int off, int len) throws IOException {
out.write(str, off, len);
}
//刷新流
public void flush() throws IOException {
out.flush();
}
//关闭流,释放相关资源
public void close() throws IOException {
out.close();
}
}
public abstract class FilterReader extends Reader {
//基础字符流
protected Reader in;
//构造方法,传入基本的字符流
protected FilterReader(Reader in) {
super(in);
this.in = in;
}
//读取一个字符
public int read() throws IOException {
return in.read();
}
//将缓冲区中数据最多len个字符读取到cbuf字符数组中
public int read(char cbuf[], int off, int len) throws IOException {
return in.read(cbuf, off, len);
}
//跳过n个字符
public long skip(long n) throws IOException {
return in.skip(n);
}
//此类中数据是否准备读取,即缓冲区中存在数据
public boolean ready() throws IOException {
return in.ready();
}
//流是否支持标记
public boolean markSupported() {
return in.markSupported();
}
//标记流中当前位置,将当前位置保存.
public void mark(int readAheadLimit) throws IOException {
in.mark(readAheadLimit);
}
//和mark()配合使用,将流当前位置重置到标记的位置
public void reset() throws IOException {
in.reset();
}
//关闭流,释放资源
public void close() throws IOException {
in.close();
}
}
FilterReader源码
public abstract class FilterReader extends Reader {
//基础字符流
protected Reader in;
//构造方法,传入基本的字符流
protected FilterReader(Reader in) {
super(in);
this.in = in;
}
//读取一个字符
public int read() throws IOException {
return in.read();
}
//将缓冲区中数据最多len个字符读取到cbuf字符数组中
public int read(char cbuf[], int off, int len) throws IOException {
return in.read(cbuf, off, len);
}
//跳过n个字符
public long skip(long n) throws IOException {
return in.skip(n);
}
//此类中数据是否准备读取,即缓冲区中存在数据
public boolean ready() throws IOException {
return in.ready();
}
//流是否支持标记
public boolean markSupported() {
return in.markSupported();
}
//标记流中当前位置,将当前位置保存.
public void mark(int readAheadLimit) throws IOException {
in.mark(readAheadLimit);
}
//和mark()配合使用,将流当前位置重置到标记的位置
public void reset() throws IOException {
in.reset();
}
//关闭流,释放资源
public void close() throws IOException {
in.close();
}
}
总结
字符流中过滤流与字节流中过滤流继承体系相差较大.而且字符过滤流其中只有FilterReader有子类PushBackReader,而FilterWriter没有子类,目前没看到实际的用处.可以留作以后扩展用.