我真的被这个问题困住了。我想知道是否可以在读取文件时排除 arraylist 中的所有元素?预先感谢您!
我的数组列表(排除列表)上有这样的元素:
test1
test2
test3
我的文件(readtest)上有 csv 数据,如下所示:
test1,off
test2,on
test3,off
test4,on
所以我期望的是在 while 循环中排除 arraylist 中的所有数据,然后输出如下:
test4,on
这是我的代码:
String exclude = "C:\\pathtomyexcludefile\\exclude.txt";
String read = "C:\\pathtomytextfile\\test.txt";
File readtest = new File(read);
File excludetest = new File(exclude);
ArrayList<String> excludelist = new ArrayList();
excludelist.addAll(getFile(excludetest));
try{
String line;
LineIterator it = FileUtils.lineIterator(readtest,"UTF-8");
while(it.hasNext()){
line = it.nextLine();
//determine here
}
catch(Exception e){
e.printStackTrace();
}
public static ArrayList<String> getFile(File file) {
ArrayList<String> data = new ArrayList();
String line;
try{
LineIterator it = FileUtils.lineIterator(file,"UTF-8");
while(it.hasNext()){
line = it.nextLine();
data.add(line);
}
it.close();
}
catch(Exception e){
e.printStackTrace();
}
return data;
}
最佳答案
可能有更有效的方法来执行此操作,但您可以使用 String.startsWith
针对 excludeList
中的每个元素检查正在读取的每一行。如果该行不以要排除的单词开头,请将其添加到 approvedLines
列表中。
String exclude = "C:\\pathtomyexcludefile\\exclude.txt";
String read = "C:\\pathtomytextfile\\test.txt";
File readtest = new File(read);
File excludetest = new File(exclude);
List<String> excludelist = new ArrayList<>();
excludelist.addAll(getFile(excludetest));
List<String> approvedLines = new ArrayList<>();
LineIterator it = FileUtils.lineIterator(readtest, "UTF-8");
while (it.hasNext()) {
String line = it.nextLine();
boolean lineIsValid = true;
for (String excludedWord : excludelist) {
if (line.startsWith(excludedWord)) {
lineIsValid = false;
break;
}
}
if (lineIsValid) {
approvedLines.add(line);
}
}
// check that we got it right
for (String line : approvedLines) {
System.out.println(line);
}
关于Java ArrayList 和 FileReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30655886/