Molag Bal
Molag Bal

Reputation: 47

How to get data blockwise from an outputstream in java?

I want to serialize a big object structure to store it to a sql database.

Object tree = getTree();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(tree);
String objectString = Base64.getEncoder().encodeToString(baos.toByteArray());

The problem is that the generated byte array by baos.toByteArray() is to large. It throws java.lang.OutOfMemoryError and it is to big to transfer it to the database at once. I'm looking for an option to get the generated byte array block by block from outputstream to work it off in a loop step by step.

Upvotes: 0

Views: 109

Answers (2)

user207421
user207421

Reputation: 310980

Forget about the base64-encoding and write the object directly to the Blob's output stream.

Upvotes: 0

jtahlborn
jtahlborn

Reputation: 53694

Write the initial OutputStream to a temporary file (using FileOutputStream). also, make sure you close the ObjectOutputStream or it will be a malformed stream. Lastly, open your temp file as a FileInputStream and use that to stream into your database.

Upvotes: 1

Related Questions