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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 qq496099229 于 2015-6-10 13:15 编辑
  1. /*
  2.         

  3. */
  4. import java.io.*;

  5. class  ObjectStreamDemo
  6. {
  7.         public static void main(String[] args) throws Exception
  8.         {
  9.                 writeObj();
  10.                 readObj();
  11.         }
  12.         //
  13.         public static void readObj() throws Exception
  14.         {
  15.                 ObjectInputStream ois=new ObjectInputStream(
  16.                         new FileInputStream("F:\\TestTXT\\obj.txt"));        //读取序列文件

  17.                 Person p=(Person)ois.readObject();

  18.                 System.out.println(p);

  19.                 ois.close();


  20.         }

  21.         public static void writeObj() throws IOException
  22.         {
  23.                 ObjectOutputStream oos=new
  24.                         ObjectOutputStream(new FileOutputStream("F:\\TestTXT\\obj.txt"));

  25.                 oos.writeObject(new Person("fsy",22,"cc"));//序列化对象类必须实现Serializable,内存里面的东西,你也看不出来
  26.         
  27.                 oos.close();
  28.         }

  29. }

复制代码


  1. import java.io.*;
  2. class Person implements Serializable    //没有方法的接口,是标记接口
  3. {
  4.         static final long serialVersionUID=42L;

  5.         private        String name;
  6.         transient int age;                                   //transient保证在堆的变量不能被序列化
  7.         static String country="cn";                   //static 存储在方法堆里面,不能被序列化
  8.         Person(String name,int age,String country)
  9.         {
  10.                 this.name=name;
  11.                 this.age=age;
  12.                 this.country=country;
  13.         }
  14.         public String toString()
  15.         {
  16.                 return name+":"+age+":"+country;
  17.         }
  18. }
复制代码


运行结果竟然是fsy:0:cc

1 个回复

倒序浏览
注意:被static或transient修饰的属性不能序列化,因为静态属性在静态区,不在堆中
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马