如何使用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
}
}
答案 0 :(得分:0)
请检查是否有null
void readObj()throws IOException,ClassNotFoundException{ //reads from file
try{
FileInputStream fis = new FileInputStream("temp1.bin");
System.out.println("1->"+fis==null);
ObjectInputStream oin = new ObjectInputStream(fis);
System.out.println("2->"+oin==null);
SerializationDemo sd = (SerializationDemo) oin.readObject();
System.out.println("3->"+sd==null);
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());
}catch(Exception e)
{
System.out.println(e.toString);}
}
请检查实际变为空的位置,然后在那里采取行动。
答案 1 :(得分:0)
为了使序列化机制能够处理所有类,本地成员变量必须是基本类型或可序列化对象。
第一个问题是SerializationDemo
的成员变量类型demo
不可序列化。
这应解决这个问题:
class demo implements Serializable{
private int demoval;
demo(){
demoval=10;
}
public int getValue(){
return demoval;
}
}
导致空例外的第二个问题是您从未设置d1
的值。确保在序列化之前设置它,否则当你尝试反序列化它时,你将尝试从null创建一个demo类的实例。简单的解决方法是添加默认构造函数:
import java.io.*;
class SerializationDemo implements Serializable //composite class
{
public SerializationDemo()
{
d1 = new demo();
}
public int value = 4;
public demo d1;
public String purpose="DEMO";
public int getValue(){
return value;
}
}