Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serializing a list of objects into a file in 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.

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.

like image 275
M.J. Avatar asked Nov 29 '11 08:11

M.J.


People also ask

How do you serialize a List of objects in Java?

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.

How do you serialize an array of objects?

We can also serialize an array of objects using the serialize() method of JSONSerializer class, this performs a shallow serialization of the target instance.

Can we serialize List in Java?

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.


1 Answers

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;)

like image 132
Stanislav Levental Avatar answered Oct 27 '22 16:10

Stanislav Levental