8

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

ryskajakub
  • 6,351
  • 8
  • 45
  • 75

3 Answers3

10

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
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I definitely know this is not a good practice, which is in my opinion no justification for not knowing this way of programming :-) – ryskajakub May 20 '10 at 12:00
  • Okay, let's assume that you know what you're doing :) You're welcome. – BalusC May 20 '10 at 12:16
5
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
  • 46,889
  • 11
  • 103
  • 119
0

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
  • 1,954
  • 2
  • 14
  • 18