用于对象序列化,将对象保存在数据库中:
This is what I use to serialize and deserialize objects to a DBMS:
/**
* Converts a serializable object to a byte array.
*/
private byte[] objectToBytes(Object object)
throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(baos);
os.writeObject(object);
return baos.toByteArray();
}
/**
* Converts a byte array to a serializable object.
*/
private Object bytesToObject(byte[] bytes)
throws IOException, ClassNotFoundException
{
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream is = new ObjectInputStream(bais);
return is.readObject();
}
then,
byte[] bytes = objectToBytes(myObject);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
pstmt.setBinaryStream(1, bais, bytes.length);
pstmt.executeUpdate();