Serializing a list of objects to a file in java

I have a list of about 20,000 objects, which, in turn, have a very huge hierarchy. I need to dump objects into a file so that I can read it later at any time during my process. Now my problem is that I worked on Java, but not much in serialization, and I don't have much knowledge on how to do this.

In this case, as far as I know, I need to use Serialization and de-serialization. Someone can help. I can also use any new API or regular Java serialization.

Sincerely.

+4
source share
5 answers

Have a look at this link http://www.java2s.com/Code/Java/File-Input-Output/Objectserialization.htm 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); 

Do not forget to implement the Serializable interface in all classes that you want to save and put the transition modifier in all the fields that you do not want to save. (e.g. closed cache List List;)

+10
source

Recently, JSON is just rage, so you can use it. Jackson is a nice api for JSON serialization / deserialization. As a bonus, you get the opportunity to interact with other platforms.

If you are not afraid of using xml JAXB

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

+1
source

Instead of saving each object separately, you can directly save the list of objects. For this, I use the code below. Although I am serializing for cloning, this should be enough 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; } } 
+1
source

below is the code for writing objects to a file using XMLEncoder, assuming your object implements the Serializable interface.

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

Below is the code for deserializing data

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

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

Writing and reading an 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); } } } 
-1
source

Source: https://habr.com/ru/post/1383591/


All Articles