Serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later (possibly in a different computer environment). This process of serializing an object is also called marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (also called unmarshalling).
public String toString(){ return"[" + id + "]: " + size; }
publicstaticvoidmain(String[] args)throws ClassNotFoundException, IOException { Random rand = new Random(); int number = 5; String header = "Worms record"; Worm[] worms = new Worm[number]; for (int i = 0; i < 5; i++) { worms[i] = new Worm(i, rand.nextInt(20)); } System.out.println(header); System.out.println(Arrays.toString(worms));
/* * Using file (FileOutputStream & FileInputStream) * */ // export to "worms.out" file ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("worms.out")); out.writeObject(header); out.writeObject(worms); out.close();
Worm[] wormsNew = new Worm[number];
// import from "worms.out" file ObjectInputStream in = new ObjectInputStream(new FileInputStream("worms.out")); String s = (String) in.readObject(); wormsNew = (Worm[]) in.readObject(); in.close();