I am learning Java serialization and deserialization, but I wonder how deserialization works.
Here is my serialization and deserialization code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Testing{
public static void main(String[] args){
Serial obj = new Serial();
Serial ObjNew = null;
try{
FileOutputStream fob= new FileOutputStream("file.src");
ObjectOutputStream oob= new ObjectOutputStream(fob);
oob.writeObject(obj);
oob.close();
}catch(Exception fnf){
fnf.printStackTrace(System.out);
}
try{
FileInputStream fis = new FileInputStream("file.src");
ObjectInputStream ois = new ObjectInputStream(fis);
ObjNew=(Serial)ois.readObject();
}
catch(IOException | ClassNotFoundException fnf){
fnf.printStackTrace(System.out);
}
System.out.println("OLD: "+obj);
System.out.println("NEW: "+ObjNew);
}
}
Here's the Serializable Class Code:
import java.io.Serializable;
public class Serial implements Serializable {
private final String ok="DONE";
@Override
public String toString(){
return ok;
}
}
Everything works fine with the above code. But when I try to deserialize an object using this code.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Testing{
public static void main(String[] args){
Serial ObjNew = null;
try{
FileInputStream fis = new FileInputStream("file.src");
ObjectInputStream ois = new ObjectInputStream(fis);
ObjNew=(Serial)ois.readObject();
}
catch(IOException | ClassNotFoundException fnf){
fnf.printStackTrace(System.out);
}
System.out.println("NEW: "+ObjNew);
}
}
and I just changed the value String ok="Do";in the Serializable Class Just to check the Deserialize output.
But it just prints Doinstead of the value DONEthat is stored in the file. Why does he print only Do?
why doesn't it read the value from the file? Any help?
user5028722
source
share