Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
SequenceInputStream

TheSequenceInputStreamclass allows you to concatenate multipleInputStreams. The
construction of aSequenceInputStreamis different from any otherInputStream.A
SequenceInputStreamconstructor uses either a pair ofInputStreams or anEnumeration
ofInputStreams as its argument:


SequenceInputStream(InputStreamfirst, InputStreamsecond)
SequenceInputStream(Enumeration <? extends InputStream>streamEnum)

Operationally, the class fulfills read requests from the firstInputStreamuntil it runs out and
then switches over to the second one. In the case of anEnumeration, it will continue through
all of theInputStreams until the end of the last one is reached.
Here is a simple example that uses aSequenceInputStreamto output the contents of
two files:


// Demonstrate sequenced input.
import java.io.;
import java.util.
;


class InputStreamEnumerator implements Enumeration {
private Enumeration files;


public InputStreamEnumerator(Vector<String> files) {
this.files = files.elements();
}

public boolean hasMoreElements() {
return files.hasMoreElements();
}

public FileInputStream nextElement() {
try {
return new FileInputStream(files.nextElement().toString());
} catch (IOException e) {
return null;
}
}
}


class SequenceInputStreamDemo {
public static void main(String args[])
throws IOException {


int c;
Vector<String> files = new Vector<String>();

files.addElement("/autoexec.bat");
files.addElement("/config.sys");
InputStreamEnumerator e = new InputStreamEnumerator(files);
InputStream input = new SequenceInputStream(e);

while ((c = input.read()) != -1) {
System.out.print((char) c);

Chapter 19: Input/Output: Exploring java.io 573

Free download pdf