day21 IO包中的其它类

来源:互联网 发布:网络多媒体箱 编辑:程序博客网 时间:2024/06/05 15:37

<1 对象的序列化>

ObjectInputStream和ObjectOutputStream 成对使用

package day21;import java.io.*;/** * Created by Administrator on 2017/2/14. */public class ObjectStreamDemo {    public static void main(String[] args) throws IOException, ClassNotFoundException {//        writeObj();        readObj();    }    public static void readObj() throws IOException, ClassNotFoundException {        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));        Person p = (Person) ois.readObject();        System.out.println(p);        ois.close();    }    public static void writeObj() throws IOException {        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));        oos.writeObject(new Person("lisi", 399, "kr"));        oos.close();    }}
package day21;import java.io.Serializable;/** * Created by Administrator on 2017/2/14. */public class Person implements Serializable{ //标记接口    //给类定义一个固定标识。就是为了序列化方便。(使得新的类还能操作曾经被序列化的对象)    public static final long serialVersionUID = 42L;    private String name;    transient int age; //非静态成员,不序列化它。它仍在堆中。    static String country = "cn"; //静态 是不能被序列化的。它在方法区中    Person(String name, int age, String country){        this.name = name;        this.age = age;        this.country = country;    }    public String toString(){        return name + ":" + age + ":" + country;    }}



0 0
原创粉丝点击