Exercise: Serialize a collection
- Save the serialization operation of a collection with multiple custom objects to a
list.txt
file. - Deserialize
list.txt
, traverse the collection, and print the object information.
case study
- Define an ArrayList collection to store Person objects
- Store the Person object in the ArrayList collection
- Create a serialized stream ObjectOutputStream object
- Use the writeObject method in the ObjectOutputStream object to serialize the collection
- Create a deserialized ObjectInputStream object
- Use the method readObject in the ObjectInputStream object to read the collection saved in the file
- Convert a collection of Object type to ArrayList type
- Traverse the ArrayList collection
- Release resources
Case realization
package com.itheima.demo04.ObjectStream;
import java.io.*;
import java.util.ArrayList;
public class Demo03Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("张三",18));
list.add(new Person("李四",19));
list.add(new Person("王五",20));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt"));
oos.writeObject(list);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("list.txt"));
Object o = ois.readObject();
ArrayList<Person> list2 = (ArrayList<Person>)o;
for (Person p : list2) {
System.out.println(p);
}
ois.close();
oos.close();
}
}
operation result
Person{name='Zhang San', age=18}
Person{name='李四', age=19}
Person{name='王五', age=20}