THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

public void run() {
try {
try {
for (char c = 'a'; c <= 'z'; c++)
out.write(c);
} finally {
out.close();
}
} catch (IOException e) {
getUncaughtExceptionHandler().
uncaughtException(this, e);
}
}
}


The TextGenerator simply writes to the output stream passed to its constructor. In the example that
stream will actually be a piped stream to be read by the main thread:


class Pipe {
public static void main(String[] args)
throws IOException
{
PipedWriter out = new PipedWriter();
PipedReader in = new PipedReader(out);
TextGenerator data = new TextGenerator(out);
data.start();
int ch;
while ((ch = in.read()) != -1)
System.out.print((char) ch);
System.out.println();
}
}


We create the Piped streams, making the PipedWriter a parameter to the constructor for the
PipedReader. The order is unimportant: The input pipe could be a parameter to the output pipe. What is
important is that an input/output pair be attached to each other. We create the new TextGenerator object,
with the PipedWriter as the output stream for the generated characters. Then we loop, reading characters
from the text generator and writing them to the system output stream. At the end, we make sure that the last
line of output is terminated.


Piped streams need not be connected when they are constructedthere is a no-arg constructorbut can be
connected at a later stage via the connect method. PipedReader.connect takes a PipedWriter
parameter and vice versa. As with the constructor, it does not matter whether you connect x to y, or y to x,
the result is the same. Trying to use a Piped stream before it is connected or trying to connect it when it is
already connected results in an IOException.


20.5.5. ByteArray Byte Streams


You can use arrays of bytes as the source or destination of byte streams by using ByteArray streams. The
ByteArrayInputStream class uses a byte array as its input source, and reading on it can never block. It
has two constructors:


publicByteArrayInputStream(byte[] buf, int offset, int count)
Free download pdf