A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 杨锦 中级黑马   /  2012-9-5 20:48  /  1464 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 杨锦 于 2012-9-5 21:57 编辑

public class ObjectOutDemo {

        public static void main(String[] args) throws IOException, IOException {
                Person  p1 = new Person("张三",15);
                Person  p2 = new Person("李四",32);
                Person  p3 = new Person("王五",23);
                Person  p4 = new Person("赵六",22);
                ArrayList<Person> list = new ArrayList<Person>();
                Collections.addAll(list, p1,p2,p3,p4);
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));
                oos.writeObject(list);                                       
                oos.close();
        }
}

评分

参与人数 1技术分 +1 收起 理由
田建 + 1

查看全部评分

3 个回复

倒序浏览

你可以查API文档:
ObjectOutputStream 只能将支持 java.io.Serializable 接口的对象写入流中。每个 serializable 对象的类都被编码,编码内容包括类名和类签名、对象的字段值和数组值,以及从初始对象中引用的其他所有对象的闭包。
所以你的程序抛出NotSerializableException异常。
  1. import java.io.*;
  2. import java.util.*;
  3. class Person implements Serializable
  4. {
  5. private String name;
  6. private int age;
  7. Person(String name,int age)
  8. {
  9. this.name = name;
  10. this.age = age;
  11. }
  12. }

  13. public class Demo {

  14. public static void main(String[] args) throws Exception{
  15. Person p1 = new Person("张三",15);
  16. Person p2 = new Person("李四",32);
  17. Person p3 = new Person("王五",23);
  18. Person p4 = new Person("赵六",22);
  19. ArrayList<Person> list = new ArrayList<Person>();
  20. Collections.addAll(list, p1,p2,p3,p4);
  21. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));
  22. ObjectInputStream ois = new ObjectInputStream (new FileInputStream("obj.txt"));
  23. try
  24. {
  25. oos.writeObject(list);
  26. System.out.println(ois.readObject());
  27. }
  28. catch (NotSerializableException e)
  29. {
  30. System.out.println("错误");
  31. }

  32. oos.close();
  33. }
  34. }
复制代码

点评

谢谢  发表于 2012-9-5 21:56

评分

参与人数 1技术分 +1 收起 理由
王德升 + 1 赞一个!

查看全部评分

回复 使用道具 举报
陈莹 发表于 2012-9-5 21:17
你可以查API文档:
ObjectOutputStream 只能将支持 java.io.Serializable 接口的对象写入流中。每个 seria ...

问一下啊,你是怎样把行号也拷过来的?
回复 使用道具 举报
吴通 发表于 2012-9-5 21:40
问一下啊,你是怎样把行号也拷过来的?

行号不是拷贝来的,你直接把代码复制过来,发表的时候就加上了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马