26
Feb

Serializing/Deserializing multiple objects (of same class)

Serializing/Deserializing multiple objects (of same class)
=============================================================

package J8Features;

import java.io.File;
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.List;

public class SerDeserialization {

	public static void main(String[] args) {
		Student obj1 = new Student(21, "Jacky1");
		Student obj2 = new Student(22, "Jacky2");
		Student obj3 = new Student(23, "Jacky3");
		Student obj4 = new Student(24, "Jacky4");
		Student obj5 = new Student(25, "Jacky5");
		Student obj6 = new Student(26, "Jacky6");

		List<Student> list = new ArrayList<>();
		list.add(obj1);
		list.add(obj2);
		list.add(obj3);
		list.add(obj4);
		list.add(obj5);
		list.add(obj6);
		File file = new File("C:\\s.ser");

		// Serialization
		try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
			oos.writeObject(list);
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// Deserialization
		try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
			List<Student> listR = (List<Student>) ois.readObject();
			for (Student s : listR)
				System.out.println(s.getId() + "::" + s.getName());
			ois.close();
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		}

	}

}


Output:
21::Jacky1
22::Jacky2
23::Jacky3
24::Jacky4
25::Jacky5
26::Jacky6