How to use SequenceInputStream

SequenceInputStream reads data from multiple inputstreams in an order. It starts with first inputstream and once it is done reading the first inputstream, it starts reading data from the next available inputstream. Two constructors are available for creating an instance of this stream. First one being

SequenceInputStream(InputStream s1, InputStream s2)

The above constructors limits us to only two inputstream. The SequenceInputStream starts reading inputstream s1 first and then s2.

If we to want have more than two inputstream to read from, then we can use the below constructor

SequenceInputStream(Enumeration<? extends InputStream> e)

Where the order of inputstream is defined by an instance of Enumeration.

One of the use cases where this stream can be used is file merging. Below is an example

package IO;

import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;

public class SequenceInputStreamDemo {
    public static void main(String[] args) {
        File file1 = new File("File1.txt");
        File file2 = new File("File2.txt");
        File file = new File("File.txt");
        try (FileInputStream fis1 = new FileInputStream(file1);
            FileInputStream fis2 = new FileInputStream(file2);
            FileOutputStream fos = new FileOutputStream(file);) {

            Enumeration inputStreams = Collections.enumeration(Arrays.asList(fis1, fis2));
            SequenceInputStream sis = new SequenceInputStream(inputStreams);

            byte[] data = new byte[1024];
            int bytesRead =;
            while(bytesRead != -1) {
                fos.write(data, 0, bytesRead);
                bytesRead =;
        } catch (FileNotFoundException excep) {
        } catch (IOException excep) {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s