Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create object output stream from an object

I want to create on ObjectOutputStream, but I don't want to persist the object in a file, so how to do that? All the tutorials(that I found) say only about the file way:

        FileOutputStream fos = new FileOutputStream("t.tmp");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(new Date());
        oos.close();

I want to store the object into a database, so I need to specify a stream in method setBinaryStream() from class PreparedStatement.

Thanks for answering...

like image 655
ryskajakub Avatar asked May 20 '10 11:05

ryskajakub


People also ask

How do I create an output stream?

Methods of OutputStreamwrite() - writes the specified byte to the output stream. write(byte[] array) - writes the bytes from the specified array to the output stream. flush() - forces to write all data present in output stream to the destination. close() - closes the output stream.

What is object output stream?

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream.

What is writeObject in Java?

writeObject(Object obj) method writes the specified object to the ObjectOutputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are written.


2 Answers

Store it in a byte array instead. You can use ByteArrayOutputStream for this. This way you can use PreparedStatement#setBytes().

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(new Date());
oos.close();
// ...
preparedStatement.setBytes(i, baos.toByteArray());

That said, this is pretty a good smell. Are you sure that you need to serialize Java objects into a database? This way they are unindexable and unsearchable. If you for example store each Person serialized in the DB, you cannot do SELECT * FROM person WHERE name = 'John' anymore. The normal practice is to do a 1:1 mapping of the entity and the DB table. The Date for example can perfectly be stored in a DATETIME/TIMESTAMP column.

like image 164
BalusC Avatar answered Sep 20 '22 20:09

BalusC


ByteArrayOutputStream bos = new ByteArrayOutputStream();

ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(new Date());
os.close();

byte[] data = bos.toByteArray();

So now you have a byte array and do what you want with it.

like image 41
Petar Minchev Avatar answered Sep 20 '22 20:09

Petar Minchev