Chapter 8. Streams in Memory

In the last several chapters, you’ve learned how to use streams to move data between a running Java program and external programs and stores. Streams can also be used to move data from one part of a Java program to another. This chapter explores three such methods. Sequence input streams chain several input streams together so that they appear as a single stream. Byte array streams allow output to be stored in byte arrays and input to be read from byte arrays. Finally, piped input and output streams allow output from one thread to become input for another thread.

Sequence Input Streams

The java.io.SequenceInputStream class connects multiple input streams together in a particular order:

public class SequenceInputStream extends InputStream

Reads from a SequenceInputStream first read all the bytes from the first stream in the sequence, then all the bytes from the second stream in the sequence, then all the bytes from the third stream, and so on. When the end of one of the streams is reached, that stream is closed; the next data comes from the next stream. Of course, this assumes that the streams in the sequence are in fact finite. There are two constructors for this class:

public SequenceInputStream(Enumeration e)
public SequenceInputStream(InputStream in1, InputStream in2)

The first constructor creates a sequence out of all the elements of the Enumeration e. This assumes all objects in the enumeration are input streams. If this isn’t the case, a ClassCastException ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.