当前位置: 移动技术网 > IT编程>开发语言>Java > Java中FilterInputStream和FilterOutputStream的用法详解

Java中FilterInputStream和FilterOutputStream的用法详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

filterinputstream
filterinputstream 的作用是用来“封装其它的输入流,并为它们提供额外的功能”。它的常用的子类有bufferedinputstream和datainputstream。
bufferedinputstream的作用就是为“输入流提供缓冲功能,以及mark()和reset()功能”。
datainputstream 是用来装饰其它输入流,它“允许应用程序以与机器无关方式从底层输入流中读取基本 java 数据类型”。应用程序可以使用dataoutputstream(数据输出流)写入由datainputstream(数据输入流)读取的数据。
filterinputstream 源码(基于jdk1.7.40):

package java.io;
public class filterinputstream extends inputstream {
  protected volatile inputstream 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();
  }
}

filteroutputstream 
filteroutputstream 的作用是用来“封装其它的输出流,并为它们提供额外的功能”。它主要包括bufferedoutputstream, dataoutputstream和printstream。
(01) bufferedoutputstream的作用就是为“输出流提供缓冲功能”。
(02) dataoutputstream 是用来装饰其它输出流,将dataoutputstream和datainputstream输入流配合使用,“允许应用程序以与机器无关方式从底层输入流中读写基本 java 数据类型”。
(03) printstream 是用来装饰其它输出流。它能为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。
filteroutputstream 源码(基于jdk1.7.40):

package java.io;

public class filteroutputstream extends outputstream {
  protected outputstream out;

  public filteroutputstream(outputstream out) {
    this.out = out;
  }

  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 {
     flush();
    } catch (ioexception ignored) {
    }
    out.close();
  }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网