Java 从对象创建对象输出流
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2873368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create object output stream from an object
提问by coubeatczech
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:
我想在 上创建ObjectOutputStream
,但我不想将对象保存在文件中,那么该怎么做呢?所有的教程(我找到的)只说文件方式:
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
.
我想将对象存储到数据库中,所以我需要在setBinaryStream()
class 的方法中指定一个流PreparedStatement
。
Thanks for answering...
谢谢回答...
采纳答案by BalusC
Store it in a byte array instead. You can use ByteArrayOutputStream
for this. This way you can use PreparedStatement#setBytes()
.
将其存储在字节数组中。您可以ByteArrayOutputStream
为此使用。这样您就可以使用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.
也就是说,这是一种很好的气味。您确定需要将 Java 对象序列化到数据库中吗?这样它们就不可索引且不可搜索。例如,如果您将每个Person
序列化存储在数据库中,您就不SELECT * FROM person WHERE name = 'John'
能再这样做了。通常的做法是做实体和DB表的1:1映射。在Date
例如可以完美被存储在DATETIME
/TIMESTAMP
列。
回答by Petar Minchev
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.
所以现在你有一个字节数组并用它做你想做的事。
回答by Nico
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.
您特别需要使用输出流写入数据库?在尝试编写输出流实现之前,我会认真考虑查看持久性 api.. 因为连接细节等,可能会变得难以管理。
have a look at link textand remember it can be used in J2SE as well.
查看链接文本并记住它也可以在 J2SE 中使用。