Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Stream in Java

People also ask

What is in memory stream java?

A memory stream is a stream whose backing store is your computer's memory. Memory streams can reduce the need for temporary buffers and files in an application. Memory streams encapsulate data stored as an unsigned byte array. The MemoryStream class is ideal for temporary storage of binary data.

What is a stream memory?

MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon creation of a MemoryStream object, or the array can be created as empty. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application.

Does java stream save memory?

No storage. Streams don't have storage for values; they carry values from a source (which could be a data structure, a generating function, an I/O channel, etc) through a pipeline of computational steps.

What is the use of ByteArrayOutputStream in java?

The ByteArrayOutputStream class of the java.io package can be used to write an array of output data (in bytes). It extends the OutputStream abstract class. Note: In ByteArrayOutputStream maintains an internal array of bytes to store the data.


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.


Does it need to support the Input and Output Streams? If not I would just use a ByteBuffer which allows you to read/write primitive types at random locations. (Up to 2 GB)

You can share a ByteBuffer between a reader and a writer.

e.g.

// 1 GB of virtual memory outside the heap.
ByteBuffer writer = ByteBuffer.allocateDirect(1024*1024*1024); 
ByteBuffer reader = writer.slice();

You can share memory between threads (e.g. Exchanger) and processes (using memory mapped files)


You can use PipedInputStream and PipedOutputStream

like this:

PipedOutputStream outstr = new PipedOutputStream();
PipedInputStream instr = new PipedInputStream(outstr);

that won't directly allow you to seek, but it does allow you to skip as many bytes you want from the input stream.

Be aware that whenever you write into the outstr it is blocked until everything is read from in instr (that is: if I remember correctly the Streams don't Buffer, but you can decorate them with a BufferedInputStream then you don't have to bother.


NIO allows you to directly transfer data within kernel memory - I'm not sure if it exactly overlaps with .NET's memory stream. Here's a simple example of mapping an entire file into memory for reading.