我有一個運算式陣列串列和一個檔案陣列串列,我正在為這些檔案做一個過濾器;過濾器也將是 Arraylist ->
假設我有一個包含 4 個檔案 [file, file, file, file] 文本檔案的陣列串列,例如,我有這 3 個運算式/條件:
[X、O、Z]
為了將檔案之一移動到過濾器陣列串列中,必須在檔案中驗證 3 個條件
ArrayList<String> XpathExpression= new ArrayList<String>();
ArrayList<File> FilterdFiles= new ArrayList<File>();
File folder = new File("Path for many files");
File[] files = folder.listFiles();
for (File file : files) {
if(file.isFile() && file.getName().endsWith(".txt")) {
//Parser here
/*******Get attribute values******/
for(String xpathExp: XpathExpression) {
if(what I have to write in the if statment to check that the three conditions are valid for the current file so i can add it to the FilterdFiles.) {
FilterdFiles.add(file);
}
else
continue;
}
我必須在 if 陳述句中寫什么來檢查這三個條件對當前檔案是否有效,以便我可以將其添加到 FilterdFiles。
uj5u.com熱心網友回復:
我無法根據您的代碼為您提供解決方案,因為它不包含足夠的資訊。但是我可以給你一個例子來幫助你解決你的問題。
下面的代碼將從包含另一個陣列中所有字串的串列中添加字串。我使用匹配的標志來跟蹤匹配。
import java.util.*;
public class Main{
public static void main(String[] args) {
String[] files = {"cat and dog", "dog", "fish dog cat", "apple", "peach"};
String[] expressions = {"dog", "cat"};
ArrayList<String> filtered = new ArrayList<>();
for(String f: files){
boolean matched = true;
for(String e: expressions){
if (!f.contains(e)) {
matched = false;
break;
}
}
if (matched) filtered.add(f);
}
System.out.println(filtered);
}
}
輸出:
[cat and dog, fish dog cat]
uj5u.com熱心網友回復:
如果所有條件都必須匹配,您可以撰寫另一個這樣的驗證方法:
private boolean validate(File file, ArrayList<String> XpathExpression){
for(String xpathExp: XpathExpression){
boolean validateResult = validate file with xpathExp;
if(validateResult != true){
return false;
}
}
return true;
}
如果validate(file, XpathExpression)回傳 true,則將檔案添加到過濾陣列串列。或者驗證是否有任何 xpathExp 匹配:
private boolean validate(File file, ArrayList<String> XpathExpression){
for(String xpathExp: XpathExpression){
boolean validateResult = validate file with xpathExp;
if(validateResult == true){
return true;
}
}
return false;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/406580.html
標籤:
