![](/img/trans.png)
[英]How to Write For Each Loop to Process Through String Array to Count Substrings
[英]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.