zxy0307's picture
Upload 2300 files
0284885 verified
Raw History Blame Contribute Delete
1.33 kB
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();
}
}