Example - InputStream:

In the example below we use ByteArrayInputStream which is a derived from InputStream Class.

It allows us to perform stream style operations on normal byte arrays.

import java.io.*;

class EX13A
{
void printInputStream(InputStream s)
{
System.out.print("[");
while (s.available() > 0)
{
System.out.print(s.read());
}
System.out.println("]");
s.reset();
}

public static void main(String args[])
{
byte buf1[] = { 1, 2, 3, 4, 5 }; // Create an input stream based on buf1.
InputStream is1 = new ByteArrayInputStream(buf1);
EX13A example = new EX13A();
example.printInputStream(is1); // Print the stream as is.
buf1[0] = 0; // Modify the array outside of the stream.
example.printInputStream(is1); // Print it again.
byte buf2[] = { 6, 7, 8, 9 };
buf1 = buf2; // ... and assign it to buf1.
example.printInputStream(is1); // Print it one last time.
InputStream is2 = new ByteArrayInputStream(buf2, 2, buf2.length - 2); //Stream that has last two bytes of array
example.printInputStream(is2); // Finally, print is2.
s }
}

Example - OutputStream

Here we use ByteArrayOutputStream which is derived from the OutputStream Class.

The toByteArray function used here converts the created buffer into a byte array.

// Create a stream with a starting internal buffer size of 1 byte.
ByteArrayOutputStream os = new ByteArrayOutputStream(1);
// Overflow initial allocated buffer size.
os.write(72); // "H"
os.write(105); // "i"
// Retrieve stream's internal buffer as a byte array.
byte buf[] = os.toByteArray();
System.out.println("Length of array is " + buf.length + "\n" + os.toString());