how to read data of composite class object from file using readObject()?
how to read data of composite object from file using readObject()? My code
is below and i got output as
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 //this is the code i have tried to execute. i got correct
output when i remove variable of type demo in SerializationDemo . but
NullPointerException when i tried for composite class. please help
me..thanks in advance
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
}
}
No comments:
Post a Comment