当前传递的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();
}
}
答案 0 :(得分:1)
在您的代码中TMap
被正确地编写和读取。问题是您不能使用字节数组作为映射的键,因为equals
比较字节数组的引用而不是内容。
将密钥包装在自定义类中,并实现equals
和hashCode
,如下所示:
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();
}
}