【问题标题】:Is it possible to save file into any collection like hashmap or hashtable?是否可以将文件保存到任何集合中,如 hashmap 或 hashtable?
【发布时间】:2020-08-23 14:46:35
【问题描述】:

我只是想将文件保存到 hashmap 或 hashtable 或任何类型的集合中。 像 HashMap = {"fileName" : "文件内容"} 但是我没有找到任何方法来做到这一点。

有人可以帮我解决这个问题吗?

提前致谢

【问题讨论】:

  • 文件有多大?您的内存是否足以容纳文件内容,如果是,您可以将文件读取为String[]byte,然后将其放入 Map

标签: java file collections hashmap hashtable


【解决方案1】:

假设您所有的 json 都存储在 src/main/resources 文件夹中,那么您可以这样做。

1.首先编写一个读取json文件的方法:

public String readJson(String fileName) throws IOException {
        final StringBuilder responseData = new StringBuilder();
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            responseData.append(line);
        }
        return responseData.toString();
    }

2.现在创建一个HashMap<String,String>,并为每个文件调用上述方法

public void storeFileDataAsMap() {
    Map<String, String> fileMap = new HashMap<>(); 
        try (Stream<Path> paths = Files.walk(Paths.get("src/main/resources"))) {
            paths
                .filter(Files::isRegularFile)
                .forEach(eachFile->{
                    try {
                        String fileName = eachFile.toAbsolutePath().toString();
                        fileMap.put(eachFile.getFileName().toString(), readJson(fileName));
                    } catch (IOException e) {
                        throw new RuntimeException("File not found exception");
                    }
                });
        } catch (IOException e) {
            throw new RuntimeException("File not found exception");
        }
    }

【讨论】:

    【解决方案2】:

    你可以试试HashMap&lt;String,String&gt;。 将文件位置存储为值会更有效,而不是将整个文件存储在 hashmap 中。

    【讨论】:

      猜你喜欢
      • 2015-12-20
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2014-07-18
      • 2015-12-08
      • 2017-05-14
      • 2020-07-17
      相关资源
      最近更新 更多