SequenceInputStream in Java

A SequenceInputStream represents the logical concatenation of other input streams. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the contained input streams.

Constructors

SequenceInputStream in Java

Methods

Screen Shot 2020-04-11 at 6.18.36 PM

Example

We will read the below two files using SequenceInputStream.

Screen Shot 2020-04-11 at 6.07.19 PM

Screen Shot 2020-04-11 at 6.07.38 PM

package com.java.io;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;

public class SequenceInputStreamExample {

    public static void main(String[] args) {
        InputStream inputStream1 = null;
        InputStream inputStream2 = null;
        SequenceInputStream sequenceInputStream = null;
        try {
            inputStream1 = new FileInputStream("/Test/TestFolder/test-file1.txt");
            inputStream2 = new FileInputStream("/Test/TestFolder/test-file2.txt");
            sequenceInputStream = new SequenceInputStream(inputStream1, inputStream2);
            int data = sequenceInputStream.read();
            while (data != -1) {
                System.out.print((char) data);
                data = sequenceInputStream.read();
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (inputStream1 != null)
                try {
                    inputStream1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (inputStream2 != null)
                try {
                    inputStream2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (sequenceInputStream != null)
                try {
                    sequenceInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

}
data1data2

Related Article

Java I/O Basics

Leave a Reply

Your email address will not be published. Required fields are marked *