Exercise: Serialize a collection

Exercise: Serialize a collection

  1. Save the serialization operation of a collection with multiple custom objects to a list.txtfile.
  2. Deserialize list.txt, traverse the collection, and print the object information.

case study

  1. Define an ArrayList collection to store Person objects
  2. Store the Person object in the ArrayList collection
  3. Create a serialized stream ObjectOutputStream object
  4. Use the writeObject method in the ObjectOutputStream object to serialize the collection
  5. Create a deserialized ObjectInputStream object
  6. Use the method readObject in the ObjectInputStream object to read the collection saved in the file
  7. Convert a collection of Object type to ArrayList type
  8. Traverse the ArrayList collection
  9. 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
After running

Person{name='Zhang San', age=18}
Person{name='李四', age=19}
Person{name='王五', age=20}

Guess you like

Origin blog.csdn.net/weixin_45966880/article/details/113914305