简体   繁体   English

ObjectInputStream读取一个空对象

[英]ObjectInputStream read a empty object

I wrote a object using ObjectOutputStream, and read it using ObjectInputStream, and tested it , I get the expected result. 我使用ObjectOutputStream编写了一个对象,并使用ObjectInputStream读取了它,并对其进行了测试,得到了预期的结果。 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;
   }

  }

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引起的。

  1. ProGuard minifyed the code, giving new shorts names to fields, like a , b , c , etc. ProGuard简化了代码,为字段abc等赋予了新的短裤名称。
  2. When serializing, the names of fields get stored into the stream. 序列化时,字段名称将存储到流中。 When reading the stream, the names must match. 读取流时,名称必须匹配。
  3. 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). 当我上次缩小代码时(对于该应用的新生产版本),ProGuard为字段指定了不同的名称(在我的情况下,这是由于ProGuard设置的更改,但也可能是由于其他原因所致,不确定ProGuard是否保证每次都使用相同的名称)。
  4. 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. 结果,当我反序列化新版本中的对象时,由于名称不匹配,所有字段均设置为默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM