Sequence Input Streams

The 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("");
URL u2 = new URL("");
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.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]);
 InputStream in = new SequenceInputStream(theStreams.elements( ));
 for (int i =; i != -1; i = )) {

Basic I/O

Introducing I/O

Output Streams

Input Streams

Data Sources

File Streams

Network Streams

Filter Streams

Filter Streams

Print Streams

Data Streams

Streams in Memory

Compressing Streams

JAR Archives

Cryptographic Streams

Object Serialization

New I/O



Nonblocking I/O

The File System

Working with Files

File Dialogs and Choosers


Character Sets and Unicode

Readers and Writers

Formatted I/O with java.text


The Java Communications API


The J2ME Generic Connection Framework


Character Sets

show all menu

Java I/O
Java I/O
ISBN: 0596527500
EAN: 2147483647
Year: 2004
Pages: 244
Similar book on Amazon © 2008-2017.
If you may any questions please contact us: