gpt4 book ai didi

Java (HashMap) - 如何保存和加载entrySet()?

转载 作者:行者123 更新时间:2023-12-02 07:01:51 27 4
gpt4 key购买 nike

我有 2 个 HashMap ,我希望在单击菜单按钮时保存这两个 HashMap ,并且我希望能够加载它们(在示例中我只保存一个)。

void saveHash(HashMap<String, Object> hash, HashMap<String, Object> logicalMatrix2) {
JFrame parentFrame = new JFrame();

JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Especifique um diretório:");
fileChooser.setAcceptAllFileFilterUsed(false);

int userSelection = fileChooser.showSaveDialog(parentFrame);

if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = new File(fileChooser.getSelectedFile() + ".alg");
Set<Entry<String, Object>> entry = hash.entrySet();
FileWriter outFile;
try {
outFile = new FileWriter(fileToSave.getAbsolutePath());
PrintWriter out = new PrintWriter(outFile);
out.println(entry);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

有了这个,我可以将entrySet()保存在txt文件中,但随后我不知道如何加载这些内容。软件将从 HashMap 为空开始,然后,通过加载过程,我希望能够相应地填充键及其各自的值。但是,考虑到它保存在 txt 文件中,我如何通过它运行“读取循环”来识别未知 key ?当我们考虑每个键的值是一个 ArrayList 时,问题会变得更加复杂。

非常感谢!

最佳答案

可能最简单的途径是使用 ObjectOutputStream而不是 PrintWriter,您可以使用 ObjectInputStream 读取结果.
这是假设 HashMap 中包含的对象是 SerializableExternalizable .
我只会序列化 HashMap 本身而不是 EntrySet。使用对象序列化时有很多注意事项(版本控制、 transient 对象、枚举常量等),所以我建议您 do some reading about the subject

XMLEncoderXMLDecoder如果您需要在 Java 环境之外读取文件或希望它们可供人类阅读,则可能会提供更多的可移植性。

关于Java (HashMap) - 如何保存和加载entrySet()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16554291/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com