SequenceInputStream Concatenates Streams
Concatenate streams with SequenceInputStream, first as a pair and then through an enumeration, and read the joined bytes in order.
Code
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
InputStream header = new ByteArrayInputStream("header\n".getBytes());
InputStream body = new ByteArrayInputStream("body\n".getBytes());
// SequenceInputStream concatenates the streams in order
try (InputStream merged = new SequenceInputStream(header, body)) {
System.out.println("merged: " + new String(merged.readAllBytes()).replace("\n", "|"));
}
// the enumeration form chains any number of streams in order
List<InputStream> parts = List.of(
new ByteArrayInputStream("a".getBytes()),
new ByteArrayInputStream("b".getBytes()),
new ByteArrayInputStream("c".getBytes()));
try (InputStream chain = new SequenceInputStream(Collections.enumeration(parts))) {
System.out.println("chain: " + new String(chain.readAllBytes()));
}
}
}How the snippet works
The snippet is organized around the class Main.
Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Watch out for
- Zero third-party dependencies — the runtime provides every API used here.
Putting it to use
Expect labeled output — merged:, chain: — when the file runs.
Core lines
InputStream header = new ByteArrayInputStream("header\n".getBytes());
InputStream body = new ByteArrayInputStream("body\n".getBytes());
Interactive Tools for This Topic
FAQ
- What does SequenceInputStream Concatenates Streams print when run?
- Execute the whole file; each printed line is prefixed with a label like `merged:`, `chain:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.