是否可以检索我保存在Java .dat文件中的对象的属性?

时间:2019-02-14 21:27:44

标签: java oop object fileoutputstream

我做了这个课,它有'Surname'和'pc'属性

public class Person implements Serializable{
    String surname;
    int pc;

    Person(String a, int c){
        this.surname = a;
        this.pc = c;
    }

并创建了一个名为“ p”的实例。我在下面名为“ people.dat”的文件中写入了对象p,然后读取了该文件。

public class Main{

    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {

        Scanner sc = new Scanner(System.in);
        String a = sc.nextLine();
        int c = sc.nextInt();
        Person p = new Person(a, c);
        System.out.println(p.surname+" "+p.pc);

        FileOutputStream foo = new FileOutputStream("people.dat");
        ObjectOutputStream oos = new ObjectOutputStream(foo);
        oos.writeObject(p);

        FileInputStream fis = new FileInputStream("people.dat");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object l = ois.readObject();
    }

}

我的问题是,既然对象已写入文件,是否可以读取'p'的属性?如果可以,我该如何访问它们?

1 个答案:

答案 0 :(得分:1)

您需要将Object强制转换为Person才能访问其成员。代替

Object l = ois.readObject();

尝试

Person l = (Person) ois.readObject();

由于反序列化的对象实际上是Person,所以它将正常工作。请注意不要将对象强制转换为错误的类型,除非您喜欢ClassCastException