在Java中将对象列表序列化为文件 [英] serializing a list of objects into a file in java
问题描述
我有大约20,000个对象的列表,这些对象又具有非常庞大的层次结构。我需要将对象转储到文件中,以便以后在处理过程中随时可以读取它。现在我的问题是,我在Java上工作,但在序列化方面工作不多,而且我对如何做到这一点也不了解。
I have a list of around 20,000 object, which in turn have a very huge hierarchy. I need to dump the objects into a file, so that i can read it later anytime during my process. Now my problem is, I have worked on Java but not that much on serialization and i dont have that much of knowledge how to do that.
在这种情况下,到目前为止我知道,我需要同时使用序列化和反序列化。谁能帮忙。我也可以使用任何新的API或普通的Java序列化。
In this case as far as i know, i need to use both Serialization ane De-Serialization. Can anyone please help. Also i can use any new API or normal Java Serialization.
注意。
推荐答案
查看此链接 http://www.java2s.com/Code/ Java / File-Input-Output / Objectserialization.htm
像这样:
Look at this link http://www.java2s.com/Code/Java/File-Input-Output/Objectserialization.htm Its something like this:
Card3 card = new Card3(12, Card3.SPADES);
System.out.println("Card to write is: " + card);
try {
FileOutputStream out = new FileOutputStream("card.out");
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(card);
oos.flush();
} catch (Exception e) {
System.out.println("Problem serializing: " + e);
}
Card3 acard = null;
try {
FileInputStream in = new FileInputStream("card.out");
ObjectInputStream ois = new ObjectInputStream(in);
acard = (Card3) (ois.readObject());
} catch (Exception e) {
System.out.println("Problem serializing: " + e);
}
System.out.println("Card read is: " + acard);
别忘了在要保存
并放入其中的所有类中实现Serializable接口在所有不想保存的字段上使用修饰符瞬态。
(例如,私有临时列表缓存;)
Don't forget to implement Serializable interface in all class you want to save and put modifier "transient" at all fields you don't want to save. (e.g. private transient List cache;)
这篇关于在Java中将对象列表序列化为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!