有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从文本文件读取/加载此HashMap?

我使用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) {
        }
    }

共 (2) 个答案

  1. # 1 楼答案

    如果您真的想手工实现(如注释所述,这已经在java.util.Properties中实现),请参阅:

    爪哇。木卫一。BufferedReader::readLine JAVA字符串::split

  2. # 2 楼答案

    从文件中读取键值并将键值存储在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();
    }