File size: 1,330 Bytes
0284885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package case_package;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class Test1 {
    public static void main(String[] args) throws IOException {
        /*
            需求:
                将多个自定义对象序列化到文件中,但是对象的个数不确定,该如何操作?
         */

        //1、序列化多个对象
        Student s1 = new Student("zhangsan", 23, "南京");
        Student s2 = new Student("lisi", 24, "重庆");
        Student s3 = new Student("wangwu", 25, "北京");

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/" +
                "zhaoxiaoyong/Documents/Java/IO_stream_project/Object_stream_module/src/rough_draft/b.txt"));

        oos.writeObject(s1);
        oos.writeObject(s2);
        oos.writeObject(s3);

        oos.close();

        //2、另一种方式
        ArrayList<Student> list = new ArrayList<>();
        list.add(s1);
        list.add(s2);
        list.add(s3);

        ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream("/Users/" +
                "zhaoxiaoyong/Documents/Java/IO_stream_project/Object_stream_module/src/rough_draft/c.txt"));

        oos2.writeObject(list);

        oos2.close();
    }
}