我创建了这个类,它具有属性'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'的Object 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'的属性?如果是这样我怎么能访问它们?
您需要将Object
投射到Person
才能访问其成员。代替
Object l = ois.readObject();
尝试
Person l = (Person) ois.readObject();
由于被反序列化的对象实际上是Person
,因此这将没有任何问题。除非你喜欢ClassCastException
s,否则小心不要试图将对象强制转换为错误的类型。