Java IO - FilterReader&FilterWriter

基本概念

字符过滤流(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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oxf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值