I just tried to read back an object I wrote to a file. I have two functions for it.
public static Serializable_test deSerialize_object(String filename)
{
File a = new File(filename);
ObjectInputStream in = null;
try{
in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(a)));
}catch(IOException e){
e.printStackTrace();
}
Serializable_test obj1 = null;
try{
obj1 = (Serializable_test) in.readObject();
in.close();
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
return obj1;
}
public static void deSerialize_object(Serializable_test obj,String filename){
File a = new File(filename);
//int objcount = 0;
ObjectInputStream in = null;
try{
in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(a)));
}catch(IOException e){
e.printStackTrace();
}
try{
obj = (Serializable_test) in.readObject();
in.close();
}catch(EOFException e){
System.out.println("END of object files reached");
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
The first method works fine… the second method is supposed to assign the read object to the passed reference but it does not work at all (the state of the passed object remains the same as the initialized state whereas its supposed to be that of the read object) is there something wrong in the code?.
This is because in Java references are passed by value. Your second method receives a copy of the reference to your object and hence updating that reference in the second method doesn’t affect the original object.
The simplest solution would be to return the object read from the serialized stream. If you really want to update an existing object with the de-serialized object, provide an mutator update method which sets the fields of the passed in object to that of the newly read object.
Also make sure you close your resources in the finally block.