问题
I wrote a object using ObjectOutputStream, and read it using ObjectInputStream, and tested it , I get the expected result. But when write the object in other machine, read it in my computer, the read object's members are empty. Could someone help me? thanks
public class TrustNet implements Serializable{
public double[][] trusts;
public double avg = 0;
public TrustNet(int size){
trusts = new double[size][size];
}
public void writeToFile(String fileName){
try(ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream(fileName))){
writer.writeObject(this);
writer.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static TrustNet readFromFile(String fileName){
try(ObjectInputStream writer = new ObjectInputStream(new FileInputStream(fileName))){
return (TrustNet) writer.readObject();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return null;
}
}
回答1:
It took me a day to figure out what's going on. I think I finally have the answer. May be it will help other people having similar problem.
In my case, the problem was due of using ProGuard.
- ProGuard minifyed the code, giving new shorts names to fields, like
a
,b
,c
, etc. - When serializing, the names of fields get stored into the stream. When reading the stream, the names must match.
- When I minifyed code the last time (for the new Production version of the app), ProGuard gave different names to fields (in my case it was due of changed ProGuard settings, but may be due of other reasons too, not sure if ProGuard guarantee the same names every time).
- As result, when I deserialize the object in the new version, because of the names are not match, all the fields set to default values.
来源:https://stackoverflow.com/questions/19674993/objectinputstream-read-a-empty-object