gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:15:45 24 4
gpt4 key购买 nike

我创建了这个类,它具有属性“Surname”和“pc”

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

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

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

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' 的属性?如果是的话我该如何访问它们?

最佳答案

您需要将Object 转换为Person 才能访问其成员。而不是

Object l = ois.readObject();

尝试

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

由于被反序列化的对象实际上是一个 Person,因此这将不会出现任何问题。只是要小心,不要尝试将对象转换为错误的类型,除非您喜欢 ClassCastExceptions。

关于java - 是否可以检索我保存在 Java .dat 文件中的对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54699312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com