[英]How to loop through multiple files to process each
I have a functioning class serverCfgParser
that works perfectly for a single file:我有一个正常工作的 class
serverCfgParser
,它非常适用于单个文件:
serverCfgParser.parseFile("src/main/resources/static/server_dev_devops_pc.cfg");
I need to change the logic so that multiple files ending with.cfg get processed.我需要更改逻辑,以便处理以 .cfg 结尾的多个文件。 I want to pass in a variable instead of a hard coded path.
我想传入一个变量而不是硬编码路径。 Ill need to loop all files in a given directory and pass those onto serverCfgParser.
我需要循环给定目录中的所有文件并将它们传递给 serverCfgParser。 I have looked at some examples but can get this to work.
我看过一些例子,但可以让它工作。
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);
}
I used the first for loop to prove to test that file paths were being populated correctly.我使用第一个 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 is complaining about Paths.get(configFile)
: JAVA 抱怨
Paths.get(configFile)
:
The method get(URI) in the type Paths is not applicable for the arguments (File)
Paths 类型中的 get(URI) 方法不适用于 arguments(文件)
I get what its complaining about, but not sure how to feed in the right params.我明白它在抱怨什么,但不知道如何输入正确的参数。 Every example I looked at is as above but for single files only, I have yet to find an example of looping through multiple files.
我查看的每个示例都如上所述,但仅针对单个文件,我还没有找到循环多个文件的示例。
Help is greatly appreciated.非常感谢您的帮助。
You could use the toPath method of the File class:您可以使用文件 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.