Java ArrayList and FileReader



我真的被这个卡住了。我想知道是否有可能在读取文件时从数组列表中排除所有元素?提前感谢!

我的数组列表(排除列表)中有这样的元素:

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;
        }

可能有更有效的方法来做到这一点,但是您可以使用String.startsWithexcludeList中的每个元素检查正在读取的每行。如果该行开头没有要排除的单词,将其添加到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);
}

如果您排除的元素是一个String对象,您可以尝试这样做:

while(it.hasNext()){
    line = it.nextLine();
    for(String excluded : excludelist){
        if(line.startsWith(excluded)){
            continue;
        }
    }  
}