该类继承自InputStream
引入了如下包
import java.io.InputStream; import java.util.Enumeration; import java.util.Vector;
该类的类头注释如下:
/** * A <code>SequenceInputStream</code> represents * the logical concatenation of other input * streams. It starts out with an ordered * collection of input streams and reads from * the first one until end of file is reached, * whereupon it reads from the second one, * and so on, until end of file is reached * on the last of the contained input streams. * * @author Author van Hoff * @since JDK1.0 */
大意如下:
SequenceInputStream相当于是其他输入流在逻辑上的队列表达形式
他开始输出从第一个输入流读取的数据,直到eof出现
然后从开始输出从第二个输入流中读取的数据以此为例,直到最后一个输入流的eof出现
该类含有以下的成员变量:
内嵌的有序输入流序列
Enumeration<? extends InputStream> e;
作为输出到程序的输入接口的输入流
InputStream in;
该类含有如下的成员方法:
构造方法:(提供输入流队列
public SequenceInputStream(Enumeration<? extends InputStream> e) { this.e = e; try { nextStream();//尝试读取第一个输入流 } catch (IOException ex) { // This should never happen throw new Error("panic");//看来是写了错代码,或者是进行了修改,永远不可能抛出IO异常 } }
构造方法:(提供两个输入流
public SequenceInputStream(InputStream s1, InputStream s2) { Vector<InputStream> v = new Vector<>(2);//使用容器装载 v.addElement(s1); v.addElement(s2); e = v.elements();//把容器转化为枚举集合 try { nextStream(); } catch (IOException ex) { // This should never happen throw new Error("panic"); } }
读取下一个队列中的输入流
final void nextStream() throws IOException { if (in != null) {//先关闭当前流 in.close(); } if (e.hasMoreElements()) {//还有剩余的元素 in = (InputStream) e.nextElement();//将下一个输入流绑定到当前输入接口上 if (in == null) throw new NullPointerException(); } else in = null;//关闭输入接口 }
返回当前位于接口处的流中的最大可无阻塞读取的字节数
public int available() throws IOException { if (in == null) { return 0; // no way to signal EOF from available() } return in.available(); }
从当前输入接口流中读取一个字节(返回读取字节的int值
public int read() throws IOException { while (in != null) {//输入接口未关闭 int c = in.read(); if (c != -1) {//字节流还有数据 return c; } nextStream();//切换下一个 } return -1; }
读取字节数据写入数组(返回实际读取长度
public int read(byte b[], int off, int len) throws IOException { if (in == null) { return -1; } else if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } do { int n = in.read(b, off, len); if (n > 0) {//读取成功 return n; } nextStream(); } while (in != null);//输入接口未关闭 return -1; }
关闭当前流并释放资源(通过重复调用nextStream来跳过并释放流资源
public void close() throws IOException { do { nextStream(); } while (in != null); }
该类十分简单,如果了解InputStream的基类以及子类特性的话,该类基本看一下就懂了。
相当于把多个输入流整合成为一个进行统一处理,在该类中只负责切换各个输入流即可。