Memory Stream in Java

Mostowski Collapse picture Mostowski Collapse · Dec 8, 2011 · Viewed 96.1k times · Source

I am looking for a memory stream implementation in Java. The implementation should be roughly modeled after the .NET memory stream implementation.

Basically I would like to have a class MemoryStream which has to factory methods:

 class MemoryStream {
     MemoryInput createInput();
     MemoryOutput createOutput();
 }

 class MemoryInput extends InputStream {
    long position();
    void seek(long pos);
 }

 class MemoryOutput extends OutputStream {
    long position();
    void seek(long pos);
 }

So once I have an instance from the class MemoryStream I should be able to concurrently simultaneously create input and output streams, which should also allow positioning in any direction. The memory stream need not be circular, it should work for small sizes well and automatically grow. The memory stream need only be confined into one process.

Any out of the box code available?

Answer

Jesper picture Jesper · Dec 8, 2011

ByteArrayInputStream and ByteArrayOutputStream is what you are looking for.

These are implementations of the interfaces InputStream and OutputStream that read from and write to a byte array in memory. For ByteArrayOutputStream, the array will grow automatically as you write data to the stream.