繁体   English   中英

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

[英]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)

Paths 类型中的 get(URI) 方法不适用于 arguments(文件)

我明白它在抱怨什么,但不知道如何输入正确的参数。 我查看的每个示例都如上所述,但仅针对单个文件,我还没有找到循环多个文件的示例。

非常感谢您的帮助。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM