如何遍历多个文件来处理每个文件

How to loop through multiple files to process each

我有一个正常工作的 class serverCfgParser,它非常适合单个文件:

serverCfgParser.parseFile("src/main/resources/static/server_dev_devops_pc.cfg");

我需要更改逻辑以便处理多个以 .cfg 结尾的文件。我想传入一个变量而不是硬编码路径。我需要循环给定目录中的所有文件并将它们传递到 serverCfgParser。我看过一些例子,但可以让它发挥作用。

File serverConfigs = new File("src/main/resources/static");
File[] files = serverConfigs.listFiles((d, name) -> name.endsWith(".cfg"));

for (File configFile : files) {
    System.out.println(configFile);
}

ServerCfgParser serverCfgParser = new ServerCfgParser();

for (File configFile : files) {
    Charset encoding = Charset.defaultCharset();
    List<String> lines = Files.readAllLines(Paths.get(configFile), encoding);
    serverCfgParser.parseFile(configFile);
}

我使用第一个 for 循环来证明文件路径被正确填充。

src\main\resources\static\server_dev_aws_app1.cfg
src\main\resources\static\server_dev_aws_app2.cfg
src\main\resources\static\server_dev_aws_app3.cfg
src\main\resources\static\server_dev_aws_app4.cfg
src\main\resources\static\server_dev_aws_app5.cfg
src\main\resources\static\server_dev_aws_app6.cfg
src\main\resources\static\server_dev_devops_app1.cfg
src\main\resources\static\server_dev_devops_app2.cfg
src\main\resources\static\server_dev_devops_app3.cfg
src\main\resources\static\server_dev_devops_app4.cfg
src\main\resources\static\server_dev_devops_app5.cfg
src\main\resources\static\server_dev_devops_app6.cfg
src\main\resources\static\server_dev_mansible_app5.cfg
src\main\resources\static\server_dev_mansible_app6.cfg
src\main\resources\static\server_test_mansible_app5.cfg
src\main\resources\static\server_test_mansible_app6.cfg

Java 抱怨 Paths.get(configFile):

The method get(URI) in the type Paths is not applicable for the arguments (File)

我明白它在抱怨什么,但我不确定如何输入正确的参数。我看过的每个例子都如上,但仅针对单个文件,我还没有找到循环遍历多个文件的例子。

您可以使用文件的 toPath 方法 class:

Charset encoding = Charset.defaultCharset();
for (File configFile : files) {
    List<String> lines = Files.readAllLines(configFile.toPath(), encoding);
    serverCfgParser.parseFile(configFile.toString());
}