【问题标题】:How to Load all .yaml files in directory using Spring/Jackson如何使用 Spring/Jackson 加载目录中的所有 .yaml 文件
【发布时间】:2019-08-19 18:04:19
【问题描述】:

我想加载一个 .yaml 文件的集合,每个文件在列表中指定一个对象。我知道如何读取特定文件并使用jackson对其进行解析,如下所示:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

MicroServiceObject object = mapper.readValue(new File("src/main/resources/microservices/retrieveAccount.yaml"), MicroServiceObject.class);

但是我想读入microservices 目录中的所有文件并将它们添加到我的数据库/列表中。

如何读入/迭代特定目录中的所有文件?

【问题讨论】:

    标签: java spring yaml


    【解决方案1】:

    使用File#listFiles 可以为您提供目录中的文件列表(以array 的形式):

    File directory = new File("src/main/resources/microservices")
    File[] files = directory.listFiles((pathname) -> pathname.getName().endsWith(".yaml"));
    

    【讨论】:

    • 谢谢,但 listFiles 返回一个 File[] 而不是一个列表。我尝试了上面的代码并得到了一个不兼容的类型错误。
    【解决方案2】:

    使用 DirectoryStream 的另一种方式可能是

    private void loadConfig() {
            ObjectMapper mapper = new ObjectMapper(new YAMLFactory())
            Path dir = Paths.get("src/main/resources/microservices");
            // creates a stream of every file in the directory. Filters by if they have the extension .yml or .yaml
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{yml,yaml}")) {
                for (Path file : stream) {
                    // map the object from a file in the directory
                    MicroServiceObject object = mapper.readValue(file.toFile(), MicroServiceObject.class);
                    // do what ever you need to with the read in config
                }
            } catch (IOException | DirectoryIteratorException x) {
                // Handle your errors here for loading in configurations
                System.err.println(x);
            }
        }
    

    源代码:https://docs.oracle.com/javase/tutorial/essential/io/dirs.html

    【讨论】:

      猜你喜欢
      • 2010-10-17
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 2012-01-17
      • 2014-04-15
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      相关资源
      最近更新 更多