导入和反序列化时显示为null的对象

时间:2018-08-01 11:23:58

标签: java serialization deserialization

当前传递的HashMap<byte[],byte[]>中的两个值都在TMap中进行了优先序列化,在程序运行时FILEPATH中可见,显示了键和值。我尝试将其更改为非静态字段,但是,当在对象的构造函数上加载TMap时,Map持有null。这是用于保存和加载TMap的代码。有人有任何建议吗?

public void loadTMap() {
    HashMap<byte[], byte[]> TMap = new HashMap<>();
    File f = new File("FILEPATH);
    if(f.exists()) {
      try {
         FileInputStream fileIn = new FileInputStream("FILEPATH");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         TMap = (HashMap<byte[], byte[]>) in.readObject();
         in.close();
         fileIn.close();
      } catch (IOException i) {
      } catch (ClassNotFoundException c) {
      }
}
}

public void saveTMap(HashMap<byte[], byte[]> TMap) {
      try {
         FileOutputStream fileOut = new FileOutputStream(FILEPATH);
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(TMap);
         out.close();
         fileOut.close();
      } catch (IOException i) {
         i.printStackTrace();
      }
}

1 个答案:

答案 0 :(得分:1)

在您的代码中TMap被正确地编写和读取。问题是您不能使用字节数组作为映射的键,因为equals比较字节数组的引用而不是内容。

将密钥包装在自定义类中,并实现equalshashCode,如下所示:

public class ByteArrayKey implements Serializable {

    private byte[] content;

    public ByteArrayKey(byte[] content) {
        this.content = content;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ByteArrayKey that = (ByteArrayKey) o;
        return Arrays.equals(content, that.content);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(content);
    }
}

然后更改您加载并保存如下方法:

public static HashMap<ByteArrayKey, byte[]> loadTMap() {
    HashMap<ByteArrayKey, byte[]> TMap = new HashMap<>();
    File f = new File(FILEPATH);
    if (f.exists()) {
        try {
            FileInputStream fileIn = new FileInputStream(FILEPATH);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            TMap = (HashMap<ByteArrayKey, byte[]>) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException i) {
            i.printStackTrace();
        } catch (ClassNotFoundException c) {
            c.printStackTrace();
        }
    }
    return TMap;
}

public static void saveTMap(HashMap<ByteArrayKey, byte[]> TMap) {
    try {
        FileOutputStream fileOut = new FileOutputStream(FILEPATH);
        ObjectOutputStream out = new ObjectOutputStream(fileOut);
        out.writeObject(TMap);
        out.close();
        fileOut.close();
    } catch (IOException i) {
        i.printStackTrace();
    }
}