There are cases where a component you’re feeding data to needs to be in the form of an InputStream. (JAXB, a package for parsing XML, is one such case. We talk about JAXB in Lesson 20.)
Suppose you’re processing an input file, you’ve got a line of text in memory, and want to pass it to something that only accepts an InputStream. Your first instinct might be to write it to a work file, aim the InputStream at that file, and let the component read it.
But aside from the housekeeping required to allocate a file and delete it when you’re done, input and output to files is one of the slowest operations a computer does. Wouldn’t it be better if the data never had to leave computer memory?
You bet your life it would.
ByteArrayOutputStream and ByteArrayInputStream
ByteArrayOutputStream is just like FileOutputStream, only instead of writing bytes to a file, it writes to memory. And (would you believe??) ByteArrayInputStream reads from memory instead of from a file.
Here’s an example of how you can use them.
// Create a ByteArrayOutputStream and write a String to it.
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
outStream.write(theString.getBytes());
// Create a ByteArrayInputStream that contains the bytes
// written to outStream.
ByteArrayInputStream inStream
= new ByteArrayInputStream(outStream.toByteArray());
// Create a new String containing the data written
// to outStream, which is now contained in inStream.
String stringFromMemory = new String(inStream.readAllBytes());
Next: Order from chaos with Generics