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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© softzhang 中级黑马   /  2015-7-31 23:36  /  160 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

import java.io.*;
class  ObjectStreamDemo
{
        public static void main(String[] args) throws Exception
        {
                //wrtieObj();
                readObj();
        }
        public static void wrtieObj() throws IOException
        {
                ObjectOutputStream oos=
                        new ObjectOutputStream (new FileOutputStream("obj.txt"));
                oos.writeObject(new Person("lisi",39));

                oos.close();
        }
        //读取一个对象
        public static void readObj() throws Exception
        {
                ObjectInputStream ois=new ObjectInputStream(new FileInputStream("obj.txt"));
                Person p=(Person)ois.readObject();
                System.out.println(p);
                ois.close();
        }
}
class Person implements Serializable
{
        public static final long serialVersionUID=42L;
         private String name;
         static String country="cn";//静态不能被序列化,他在方法区
         transient int age;//非静态的不想被序列化就前面加 transient
        Person(String name,int age,String country)
        {
                this.name=name;
                this.age=age;
        }
        public String toString()
        {
                return name+":"+age+":"+country;
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马