黑马程序员技术交流社区

标题: 将类存中的数据存在硬盘上 [打印本页]

作者: softzhang    时间: 2015-7-31 23:36
标题: 将类存中的数据存在硬盘上
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;
        }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2