[英]How do I read / load this HashMap from a text file?
I have used a HashMap to store information that I needed on a text document using the code below, how would I now go about loading the data back into my program, currently the saving works just fine. 我使用HashMap使用下面的代码在文本文档中存储我需要的信息,现在我将如何将数据加载回我的程序,目前保存工作正常。
The text file currently stores 文本文件当前存储
KEY=VALUE
so for example my text file would be: 所以例如我的文本文件将是:
1=value
2=value
3=value
The current way I save things to this file (not sure if relevant) is this: 我将东西保存到此文件的当前方式(不确定是否相关)是这样的:
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) {
}
}
If you really want to that by hand (as the comments have stated, this is already implemented in java.util.Properties), refer to: 如果您真的想手动(如评论所述,这已在java.util.Properties中实现),请参阅:
java.io.BufferedReader::readLine java.lang.String::split java.io.BufferedReader :: readLine java.lang.String :: split
An example to read key value from file and to store key value inside HashMap. 从文件中读取键值并在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.