views:

164

answers:

3

Hi, 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...

+3  A: 
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.

Petar Minchev
+1  A: 

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.

BalusC
I definitely know this is not a good practice, which is in my opinion no justification for not knowing this way of programming :-)
coubeatczech
Okay, let's assume that you know what you're doing :) You're welcome.
BalusC
A: 

you specifically need to use an outputstream to write to a database? I would seriously consider looking at the persistence api before attempting to write an outputstream implementation.. since connection details etc, might get tricky to manage.

have a look at link text and remember it can be used in J2SE as well.

Nico