Using Java Streams to Work with Memory

We spoke earlier about streams being abstract metaphors for files or, more precisely, any type of input/output mechanism. With streams, for example, you can write data to a byte array, which is essentially a location in the computer's memory. ByteArrayInputStream and ByteArrayOutputStream allow reading and writing to and from memory. You might want to look them up in the Java API documentation.

Instead of passing a file stream to a stream derivation, you can pass a byte array stream. Here's the earlier example showing this (the differences are in bold).

from java.io import ObjectOutputStream, ByteArrayOutputStream
bytes = ByteArrayOutputStream()
oos = ObjectOutputStream(bytes) class MyClass: def __init__(self): ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython 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.