Sequence Input Streams
The java.io.SequenceInputStream class connects multiple input streams together in a particular order. A SequenceInputStream first reads all the bytes from the first stream in the sequence, then all the bytes from the second stream in the sequence, then all the bytes from the third stream, and so on. When the end of one stream is reached, that stream is closed; the next data comes from the next stream. This class has two constructors:
public SequenceInputStream(Enumeration e) public SequenceInputStream(InputStream in1, InputStream in2)
The first constructor creates a sequence out of all the elements of the Enumeration e. This assumes all objects in the enumeration are input streams. If this isn't the case, a ClassCastException will be thrown the first time a read is attempted from an object that is not an InputStream. The use of an Enumeration instead of an Iterator is a little old-fashioned. However, this class goes all the way back to Java 1.0, and Sun has never felt compelled to enhance it. In Java 5, this constructor has been retrofitted with generics, making it a tad more typesafe:
public SequenceInputStream(Enumeration e)
However, it does exactly the same thing.
The second constructor creates a sequence input stream that reads first from in1, then from in2. Note that in1 or in2 may themselves be sequence input streams, so repeated applications of this constructor allows a sequence input stream with an indefinite number of underlying streams to be created. For example, to read the home pages of both Yahoo and Google, you might do this:
URL u1 = new URL("http://www.yahoo.com/"); URL u2 = new URL("http://www.google.com"); SequenceInputStream sin = new SequenceInputStream( u1.openStream(), u2.openStream( ));
Examples 9-1reads a series of filenames from the command line, creates a sequence input stream from file input streams for each file named, and then copies the contents of all the files onto System.out.
Example 9-1. The SequencePrinter program
import java.io.*; import java.util.*; public class SequencePrinter { public static void main(String[] args) throws IOException { Vector theStreams = new Vector( ); for (int i = 0; i < args.length; i++) { FileInputStream fin = new FileInputStream(args[i]); theStreams.addElement(fin); } InputStream in = new SequenceInputStream(theStreams.elements( )); for (int i = in.read(); i != -1; i = in.read( )) { System.out.write(i); } } } |