[英]How do I read / load this HashMap from a text file?
我使用HashMap使用下面的代碼在文本文檔中存儲我需要的信息,現在我將如何將數據加載回我的程序,目前保存工作正常。
文本文件當前存儲
KEY=VALUE
所以例如我的文本文件將是:
1=value
2=value
3=value
我將東西保存到此文件的當前方式(不確定是否相關)是這樣的:
public void save(HashMap<Integer, String> map) {
try {
File zone1 = new File("zones/zone1");
FileOutputStream fileOut = new FileOutputStream(zone1);
PrintWriter print = new PrintWriter(fileOut);
for (Map.Entry<Integer, String> m : map.entrySet()) {
print.println(m.getKey() + "=" + m.getValue());
}
print.flush();
print.close();
print.close();
} catch (Exception e) {
}
}
如果您真的想手動(如評論所述,這已在java.util.Properties中實現),請參閱:
java.io.BufferedReader :: readLine java.lang.String :: split
從文件中讀取鍵值並在HashMap中存儲鍵值的示例。
try (InputStream input = new FileInputStream("path/to/file")) {
Map<Integer,String> loadedFromTextFileHashMap=new HashMap<>();
Properties prop = new Properties();
prop.load(input);
prop.forEach((key, value) -> loadedFromTextFileHashMap.put(Integer.valueOf(key.toString()), value.toString()));
} catch (IOException io) {
io.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.