如何使用 Spring/Jackson 加载目录中的所有 .yaml 文件



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

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

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

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

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

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

使用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

最新更新