我真的很喜欢这个。我想知道在阅读文件时是否可以从arraylist中排除所有元素?提前谢谢!
我的arraylist(excludelist)上有这样的元素:
test1
test2
test3
我的文件(readtest)上有csv数据,如下所示:
test1,off
test2,on
test3,off
test4,on
所以我期待的是在while循环中排除arraylist中的所有数据,然后输出如下:
TEST4,上
这是我的代码:
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;
}
答案 0 :(得分:1)
可能有更有效的方法可以执行此操作,但您可以使用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);
}
答案 1 :(得分:0)
如果您排除的元素是String
个对象,您可以尝试这样的事情:
while(it.hasNext()){
line = it.nextLine();
for(String excluded : excludelist){
if(line.startsWith(excluded)){
continue;
}
}
}