Object流的一般用法

原创
2017/07/12 22:36
阅读数 21

import java.io.*;

/**
 * Created by wang on 2017/7/12.
 */
public class TestObject {
}

class Person implements Serializable {
    private String name;
    private int age;
    private String race;
    private String location;

    public Person(String name, int age, String race, String location) {
        this.name = name;
        this.age = age;
        this.race = race;
        this.location = location;
    }

    @Override
    public String toString() {
        return name+" "+ age + " " + race + " " + location;
    }
}

class Test {
    public static void main(String[] args) {
        Person aPerson = new Person("wzong",28,"yellow","许以");
        System.out.println(aPerson);

        try {
            ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream("d:/dayuan/day24/object.dat"));
            out.writeObject(aPerson);
            out.close();

            ObjectInputStream in = new ObjectInputStream(
                    new FileInputStream("d:/dayuan/day24/object.dat"));

            Person bPerson = (Person) (in.readObject());
            out.close();
            System.out.println(bPerson);
            System.out.println(aPerson == bPerson);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

1    需要实现Serializable接口;

2    有读入读出的标准格式;

3    数据储存在dat文件中;

4    读入读出的对象数据是连个对象;

5    需要处理ClassNotFoundException异常;

展开阅读全文
打赏
2
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
2
分享
返回顶部
顶部