Java(HashMap)-如何保存和加载entrySet()?
我有两个hashmaps,我希望在单击菜单按钮时保存这两个hashmaps,并且我希望能够加载它们(在示例中,我只保存一个)Java(HashMap)-如何保存和加载entrySet()?,java,hashmap,save,key,Java,Hashmap,Save,Key,我有两个hashmaps,我希望在单击菜单按钮时保存这两个hashmaps,并且我希望能够加载它们(在示例中,我只保存一个) void saveHash(HashMap hash,HashMap logicalmatrix){ JFrame parentFrame=新的JFrame(); JFileChooser fileChooser=新的JFileChooser(); setDialogTitle(“specifique um diretório:”); fileChooser.SetAcc
void saveHash(HashMap hash,HashMap logicalmatrix){
JFrame parentFrame=新的JFrame();
JFileChooser fileChooser=新的JFileChooser();
setDialogTitle(“specifique um diretório:”);
fileChooser.SetAcceptableFileFilterUsed(false);
int userSelection=fileChooser.showsavedilog(parentFrame);
if(userSelection==JFileChooser.APPROVE\u选项){
File fileToSave=新文件(fileChooser.getSelectedFile()+“.alg”);
Set entry=hash.entrySet();
文件写入器输出文件;
试一试{
outFile=newfilewriter(fileToSave.getAbsolutePath());
PrintWriter out=新的PrintWriter(输出文件);
out.println(条目);
out.close();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}
有了它,我可以将entrySet()保存在一个txt文件中,但是我不知道如何重新加载此内容。软件将以HashMap为空开始,然后,通过加载过程,我希望能够相应地填充键及其各自的值。但是,考虑到它保存在一个txt文件中,我如何通过它运行“读取循环”来识别未知的密钥呢?当我们考虑每个密钥的值是一个数组时,问题变得更加复杂。< /P>
多谢各位 最简单的方法可能是使用打印机而不是PrintWriter,您可以使用打印机读取结果。
这是假设HashMap中包含的对象为或。
我只是序列化HashMap本身,而不是entrySet。 在使用对象序列化时,有许多注意事项(版本控制、瞬态对象、枚举常量等),因此我建议您
如果您需要在Java环境之外读取文件,或者希望这些文件是人类可读的,则可以允许更大的可移植性。除了使用其他人提到的序列化之外,另一种探索途径是使用JSON作为持久格式。您可以使用来实现这一点。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();
}
}
}