Java ArrayList 和 FileReader

标签 java arraylist bufferedreader

我真的被这个问题困住了。我想知道是否可以在读取文件时排除 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/

相关文章:

java - 线程 "main"java.lang.SecurityException : Prohibited package name: java. sql 中的异常

JavaFX 将抽象类对象添加到 arraylist

java - 有没有办法在 JTextArea 中支持真正的回车而不换行?

java - 关闭 BufferedReader 后仍有资源泄漏

java - 从用户输入中搜索 arraylist<String[]>

java - 使用 BufferedReader 将字符串转换为 int

java - 将 C 转换为 Java - 指针查询

java - jsp生成的servlet扩展到哪个类

java - Validate接口(interface)的继承设计

java - 关联列表,Arraylist Java