How do I use a SequenceInputStream to connect several FileInputStreams?
Author: Deron Eriksson
Description: This Java tutorial describes how to use a SequenceInputStream to connect several FileInputStreams.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


A SequenceInputStream can act as a single InputStream that can represent the streams of several other InputStreams in sequence. As an example, the SequenceInputStreamTest class below creates 3 FileInputStreams to files and then adds these to a Vector of InputStreams. It gets an Enumeration to the Vector and passes the Enumeration to the constructor of the SequenceInputStream. SequenceInputStreamTest reads all of the content from the SequenceInputStream and outputs it to the console via System.out.

SequenceInputStreamTest.java

package test;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;

public class SequenceInputStreamTest {

	public static void main(String[] args) throws Exception {

		FileInputStream fis1 = new FileInputStream("testfile1.txt");
		FileInputStream fis2 = new FileInputStream("testfile2.txt");
		FileInputStream fis3 = new FileInputStream("testfile3.txt");

		Vector<InputStream> inputStreams = new Vector<InputStream>();
		inputStreams.add(fis1);
		inputStreams.add(fis2);
		inputStreams.add(fis3);

		Enumeration<InputStream> enu = inputStreams.elements();
		SequenceInputStream sis = new SequenceInputStream(enu);

		int oneByte;
		while ((oneByte = sis.read()) != -1) {
			System.out.write(oneByte);
		}
		System.out.flush();
	}
}

I placed messages in testfile1.txt, testfile2.txt, and testfile3.txt to distinguish them.

testfile1.txt

this is testfile1

testfile2.txt

this is testfile2

testfile3.txt

this is testfile3

When I executed SequenceInputStreamTest, the following was output to the console.

this is testfile1
this is testfile2
this is testfile3

We can see that all of content of the FileInputStreams was strung together, and this was based on their order in the the Enumeration that was passed to the constructor of the SequenceInputStream.