- //注意导包
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectOutputStream;
- import java.io.Serializable;
- import java.util.*;
- public class Test{
- public static void main(String[] args) throws IOException {
- Person p1 = new Person("张三",23);//Person “P”大写
- Person p2 = new Person("李四",24);
- Person p3 = new Person("王五",25);
-
- List<Person> list = new ArrayList<Person>();//注意泛型写法格式
- list.add(p1);
- list.add(p2);
- list.add(p3);
- ObjectOutputStream oos=null;
- try {
- oos = new ObjectOutputStream(new FileOutputStream("aa.txt"));
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- oos.writeObject(list);
- oos.close();
-
- }
- }
- //程序中用到的Person类
- class Person implements Serializable{
- private String name;
- private int age;
- Person(){}
- Person(String name,int age){
- this.name=name;
- this.age=age;
- }
- }
复制代码 上面代码运行成功,序列化生成aa.txt文档。
|