Java IO - FilterInputStream&FilterOutputStream

基本概念

FilterInputStream / FilterOutputStream (过滤输出流/过滤输入流)这两个类分别继承自 Inpustream 与 OutputStream ,提供的作用 “封装其它的输入流,并为它们提供额外的功能“。

FilterInputStream和FilterOutputStream 本身并没给出其它额外的功能实现,只是做了一层简单地封装,实现额外功能的实际是它们的子类。这也正是装饰者模式的应用。


源码分析

1.FilterInputStream

类结构图

这里写图片描述


成员变量

//代表要操作的流
protected volatile InputStream in;

构造函数

// 将流赋于成员变量 in,说明操作的并不是输入流本身
protected FilterInputStream(InputStream in) {
    this.in = in;
}

剩余方法, 通过调用要过滤的流本身的方法来实现。

public int read() throws IOException {
    return in.read();
}

public int read(byte b[]) throws IOException {
    return read(b, 0, b.length);
}

public int read(byte b[], int off, int len) throws IOException {
    return in.read(b, off, len);
}


public long skip(long n) throws IOException {
    return in.skip(n);
}


public int available() throws IOException {
    return in.available();
}


public void close() throws IOException {
    in.close();
}


public synchronized void mark(int readlimit) {
    in.mark(readlimit);
}


public synchronized void reset() throws IOException {
    in.reset();
}


public boolean markSupported() {
    return in.markSupported();
}
}

2.FilterOutputStream

结构图

这里写图片描述


成员变量

// 表示要过滤的输出流
protected OutputStream out;

构造函数

// 将流赋于成员变量 out,说明操作的并不是输出流本身
public FilterOutputStream(OutputStream out) {
    this.out = out;
}

writer 方法,与 FilterInputstream 不同,它并不是全部调用流本身的 writer 方法。

  • ① 通过调用要过滤的输出流本身的方法。

  • ②③ 在本类中定义,具体的实现关系如 ② -> ③ -> ①

// ①写入单个字符
public void write(int b) throws IOException {
    out.write(b);
}

// ②写入字符数组
public void write(byte b[]) throws IOException {
    write(b, 0, b.length);
}

// ③写入字符数组的某一部分
public void write(byte b[], int off, int len) throws IOException {
    if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
        throw new IndexOutOfBoundsException();

    for (int i = 0; i < len; i++) {
        write(b[off + i]);
    }
}

剩余的方法

public void flush() throws IOException {
    out.flush();
}

public void close() throws IOException {
    try {
        // 关键 -> 执行 close 之前会调用 flush
        flush();
    } catch (IOException ignored) {
    }
    out.close();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

oxf

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

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

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

打赏作者

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

抵扣说明:

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

余额充值