Java SequenceReader-class And Method Code Example


Here is an example of how you might use the SequenceReader class from the org.apache.commons.io package in Java:

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Reader;
import org.apache.commons.io.input.SequenceReader;

public class MyClass {

    public void doSomethingWithSequenceReader() throws Exception {
        // Create a byte array input stream
        byte[] data1 = new byte[] {1, 2, 3, 4, 5};
        InputStream inputStream1 = new ByteArrayInputStream(data1);

        // Create another byte array input stream
        byte[] data2 = new byte[] {6, 7, 8, 9};
        InputStream inputStream2 = new ByteArrayInputStream(data2);

        // Create a sequence reader
        Reader sequenceReader = new SequenceReader(inputStream1, inputStream2);

        // Read data from the sequence reader
        int value = sequenceReader.read();
        while (value != -1) {
            System.out.println(value);
            value = sequenceReader.read();
        }
    }
}

The SequenceReader class is a utility class that allows multiple readers to be read in sequence as if they were one reader. In this example, we create two ByteArrayInputStream and passed them to the SequenceReader constructor, it will read the data from both streams in the order they were added, as if they were one continuous reader.

You can also pass multiple Reader or InputStream objects to the SequenceReader constructor, to create a composite reader that reads from multiple sources.

The SequenceReader class also provides a skip(long n) method to skip a specific number of characters and a ready() method to check if there is any data available to read from the reader.

It is important to close the SequenceReader after you are done with it to release the resources associated with the underlying readers.