SequenceInputStream example program in Java

By: Reema sen Viewed: 153347 times  Printer Friendly Format    


The SequenceInputStream class allows you to concatenate multiple InputStreams. The construction of a SequenceInputStream is different from any other InputStream. A SequenceInputStream constructor uses either a pair of InputStreams or an Enumeration of InputStreams as its argument:

SequenceInputStream(InputStream first, InputStream second)
SequenceInputStream(Enumeration streamEnum)

Operationally, the class fulfills read requests from the first InputStream until it runs out and then switches over to the second one. In the case of an Enumeration, it will continue through all of the InputStreams until the end of the last one is reached. Here is a simple example that uses a SequenceInputStream to 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 files) {
this.files = files.elements();
}
public boolean hasMoreElements() {
return files.hasMoreElements();
}
public Object nextElement() {
try {
return new FileInputStream(files.nextElement().toString());
} catch (Exception e) {
return null;
}
}
}
class SequenceInputStreamDemo {
public static void main(String args[]) throws Exception {
int c;
Vector files = new Vector();
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);
}
input.close();
}
}

This example creates a Vector and then adds two filenames to it. It passes that vector of
names to the InputStreamEnumerator class, which is designed to provide a wrapper on
the vector where the elements returned are not the filenames but rather open
FileInputStream
s on those names. The SequenceInputStream opens each file in turn,
and this example prints the contents of the two files.

This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial