serializing a list of objects into a file in java

2020-08-26 10:50发布

问题:

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.

回答1:

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



回答2:

Rather than saving every object individually you can directly save the list of objects. I am using below code to achieve this. Although I am serializing for cloning, it should be sufficient to learn the basics.

public static List<EmpoyeeTO> deepCloneList( List<EmpoyeeTO> objectList) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(objectList);
            oos.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            return (List<EmpoyeeTO>) ois.readObject();
        }catch(EOFException eof){
            return objectList;
        } 
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


回答3:

JSON is all the rage recently so you can use that. Jackson is a nice api for JSON serialization/deserialization. As a bonus you get interoperability with other platforms.

If you're not affraid of xml use JAXB

Of course you can always use binary serialization, but IMO text is easier to manage than blobs.



回答4:

below is the code to write objects to file using XMLEncoder, assuming that your object implements Serializable Interface.

    FileOutputStream os =new FileOutputStream("c:/temp/serialized.xml");
    XMLEncoder encoder=new XMLEncoder(os);
    encoder.writeObject(objectToBeSerialized);
    encoder.close();

Below is the code to deserializ the Data

    FileInputStream is=new FileInputStream("c:/temp/serialized.xml");
    XMLDecoder decoder=new XMLDecoder(is);
    Object object=(Object)decoder.readObject(); 
    decoder.close();


回答5:

I give you a sample

import java.io.Serializable;

public class Account implements Serializable {

    private int accountNo;
    private String custName;
    private int balance;

    /** Creates a new instance of Account    */
    public Account(int accNo, String name, int bal) {
        this.accountNo = accNo;
        this.custName = name;
        this.balance = bal;
    }

    @Override
    public String toString() {
        String str = "Account No:" + this.accountNo;
        str += "\nCustomer name:" + this.custName;
        str += "\nBalance:" + this.balance;
        return str;
    }
}

Write and read object

package me.dev;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

    public void writeObject(ArrayList<Object> listAccount) throws IOException {
        //Create FileOutputStream to write file
        FileOutputStream fos = new FileOutputStream("C:\\bank.datum");
        //Create ObjectOutputStream to write object
        ObjectOutputStream objOutputStream = new ObjectOutputStream(fos);
        //Write object to file
        for (Object obj : listAccount) {

            objOutputStream.writeObject(obj);
            objOutputStream.reset();
        }
        objOutputStream.close();
    }

    public ArrayList<Account> readObject() throws ClassNotFoundException, IOException {
        ArrayList<Account> listAccount = new ArrayList();
        //Create new FileInputStream object to read file
        FileInputStream fis = new FileInputStream("C:\\bank.datum");
        //Create new ObjectInputStream object to read object from file
        ObjectInputStream obj = new ObjectInputStream(fis);
        try {
            while (fis.available() != -1) {
                //Read object from file
                Account acc = (Account) obj.readObject();
                listAccount.add(acc);
            }
        } catch (EOFException ex) {
            //ex.printStackTrace();
        }
        return listAccount;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ClassNotFoundException {
        try {
            // TODO code application logic here
            ArrayList<Object> listAcc = new ArrayList<Object>();
            listAcc.add(new Account(1, "John", 1000));
            listAcc.add(new Account(2, "Smith", 2000));
            listAcc.add(new Account(3, "Tom", 3000));
            Main main = new Main();
            main.writeObject(listAcc);
            ArrayList<Account> listAccount = main.readObject();
            System.out.println("listisze:" + listAccount.size());
            if (listAccount.size() > 0) {
                for (Account account : listAccount) {
                    System.out.println(((Account) account).toString());
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}