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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 心在左边跳 中级黑马   /  2015-7-9 14:10  /  505 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

操作对象
ObjectInputStream和ObjectOutputStream

  • 被操作的对象需要Serializable(标记接口)
    ObjectOutputStream 和 ObjectInputStream 分别与 FileOutputStream 和 FileInputStream 一起使用时,可以为应用程序提供对对象图形的持久存储。

静态不能被序列化,序列化的是堆内的对象,静态的在方法区

  1. import java.io.*;
  2. public class ObjectStreamDemo {
  3.     public static void main(String[] args) throws Exception {
  4.         writeObj();
  5.         readObj();
  6.     }
  7.     //写入对象
  8.     public static void writeObj() throws IOException{
  9.         ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream("obj.txt"));
  10.         oos.writeObject(new Person("lisi",39));
  11.         oos.close();
  12.     }
  13.     //读取对象
  14.     public static void readObj() throws IOException, ClassNotFoundException{
  15.         ObjectInputStream ois= new ObjectInputStream(new FileInputStream("person.obj"));
  16.         Person p=(Person)ois.readObject();
  17.         System.out.println(p);
  18.         ois.close();
  19.     }
  20. }
  21. //该接口没有方法,称为标记接口
  22. class Person implements Serializable{
  23.     String name;
  24.     //transient修饰表示虽然在堆内存中,不可被序列化
  25.     transient int age;
  26.     Person(String name,int age){
  27.         this.name=name;
  28.         this.age=age;
  29.     }
  30.     public String toString(){
  31.         return this.name+":"+this.age;
  32.     }
  33. }
复制代码



3 个回复

倒序浏览
眼花缭乱那。。。。。呵呵呵呵呵呵
回复 使用道具 举报
Love丶cd 发表于 2015-7-9 14:32
眼花缭乱那。。。。。呵呵呵呵呵呵

为啥?我写的乱七八糟?
回复 使用道具 举报
哥们 就花了20天就把基础全看完了 速度好看啊
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马