Java IO - FilterReader&FilterWriter

来源:互联网 发布:网络血滴子是什么意思 编辑:程序博客网 时间:2024/06/10 01:40

基本概念

字符过滤流(FilterReader/FilterWriter)与 字节过滤流(FilterInputStream / FilterOutputStream )的原理一致,都是通过操作要过滤的流本身的方法来实现。

不同就是字符过滤流是抽象类,而字节过滤流不是。


源码分析

1.FilterReader

类结构图

这里写图片描述


观察源码,发现在 FilterReader 中不外乎地都调用流本身的方法来实现各种操作,这点与 FilterInputStream 一致。

public abstract class FilterReader extends Reader {    //代表要操作的流    protected Reader in;    protected FilterReader(Reader in) {        super(in);        // 将流赋于成员变量 in,说明操作的并不是输入流本身        this.in = in;    }    public int read() throws IOException {        return in.read();    }    public int read(char cbuf[], int off, int len) throws IOException {        return in.read(cbuf, off, len);    }    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);    }    public void reset() throws IOException {        in.reset();    }    public void close() throws IOException {        in.close();    }}

2.FilterWriter

类结构图

这里写图片描述


与字节过滤流不同:

  • write 操作全部调用输出流本身的方法。

  • 调用 close 方法之前不会调用 flush 方法。

public abstract class FilterWriter extends Writer {    // 表示要过滤的输出流    protected Writer out;    protected FilterWriter(Writer out) {        super(out);        // 将流赋于成员变量 out,说明操作的并不是输出流本身        this.out = out;    }    public void write(int c) throws IOException {        out.write(c);    }    public void write(char cbuf[], int off, int len) throws IOException {        out.write(cbuf, 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();    }}
0 0
原创粉丝点击