如何使用 readObject() 从文件中读取复合对象的数据?我的代码在下面,输出为
version=4
purpose is DEMO
value=4
Exception in thread "main" java.lang.NullPointerException
at Serializations.readObj(PS_Task3.java:39)
at PS_Task3.main(PS_Task3.java:46)
Press any key to continue . . .
//PS_Task3.java //这是我试图执行的代码。当我在 SerializationDemo 中删除 demo 类型的变量时,我得到了正确的输出。但是当我尝试复合类时出现 NullPointerException。请帮助我..提前谢谢
import java.io.*;
class SerializationDemo implements Serializable //composite class
{
public int value = 4;
public demo d1;
public String purpose="DEMO";
public int getValue(){
return value;
}
}
class demo{
private int demoval;
demo(){
demoval=10;
}
public int getValue(){
return demoval;
}
}
class Serializations {
void writeObj()throws IOException{ //writes into file
FileOutputStream fos = new FileOutputStream("temp1.bin");
ObjectOutputStream oos = new ObjectOutputStream(fos);
SerializationDemo sd = new SerializationDemo();
oos.writeObject(sd);
oos.flush();
oos.close();
}
void readObj()throws IOException,ClassNotFoundException{ //reads from file
FileInputStream fis = new FileInputStream("temp1.bin");
ObjectInputStream oin = new ObjectInputStream(fis);
SerializationDemo sd = (SerializationDemo) oin.readObject();
System.out.println("version="+sd.value);
System.out.println("purpose is "+sd.purpose);
System.out.println("value="+sd.getValue());
System.out.println("value="+sd.d1.getValue());
}
}
public class PS_Task3{
public static void main(String args[]) throws IOException,ClassNotFoundException {
Serializations s = new Serializations();
s.writeObj();
s.readObj(); //here i got the error
}
}