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...
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.
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.
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.
精彩评论