Java
Java IO

Java IO 20 - FilterWriter和FilterReader详解

简介:流是一组有顺序的,有起点和终点的字节集合。是对设备文件间数据传输的总称和抽象。

1. FilterWriter和FilterReader介绍

与FilterOutputStream类似,FilterWriter的作用也是用来封装其它的输出流,并为它们提供额外的功能,该类并不是很常用。相应的,FilterWriter也有相应的FilterReader,FilterReader的常用的子类有PushbackReader,与PushbackInputStream类似。

2. FilterWriter和FilterReader源码

下面是FilterWriter的源码,基于JDK 1.7.0_07:

  • 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);
  • }
  • 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();
  • }
  • }

下面是FilterReader的源码,基于JDK 1.7.0_07:

  • 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();
  • }
  • 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();
  • }
  • }

从这两个类的源码可以得知,它们都是抽象类,在实现上只是简单地调用包装类的相应方法而已。