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.
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.
Regards.
In Java, ArrayList class is serializable by default. It essentially means that we do not need to implement Serializable interface explicitly in order to serialize ArrayList. We can directly use ObjectOutputStream to serialize ArrayList, and ObjectInputStream to deserialize an arraylist object.
We can also serialize an array of objects using the serialize() method of JSONSerializer class, this performs a shallow serialization of the target instance.
Serializing ArrayList: In Java, the ArrayList class implements a Serializable interface by default i.e., ArrayList is by default serialized. We can just use the ObjectOutputStream directly to serialize it.
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);
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;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With