我做了这个课,它有'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'的属性?如果可以,我该如何访问它们?
答案 0 :(得分:1)
您需要将Object
强制转换为Person
才能访问其成员。代替
Object l = ois.readObject();
尝试
Person l = (Person) ois.readObject();
由于反序列化的对象实际上是Person
,所以它将正常工作。请注意不要将对象强制转换为错误的类型,除非您喜欢ClassCastException
。