【问题标题】:Java ArrayList and FileReaderJava ArrayList 和 FileReader
【发布时间】:2015-06-04 23:28:02
【问题描述】:

我真的很喜欢这个。我想知道是否可以在读取文件时从 arraylist 中排除所有元素?提前谢谢!

我的 arraylist(excludelist) 上有这样的元素:

test1
test2
test3

我的文件(readtest)上有这样的 csv 数据:

test1,off
test2,on
test3,off
test4,on

所以我期望的是在 while 循环中从 arraylist 中排除所有数据,然后输出如下:

测试4,开启

这是我的代码:

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

【问题讨论】:

  • 你有什么问题?到目前为止,您做了哪些调试工作?

标签: java arraylist bufferedreader


【解决方案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);
}

【讨论】:

  • 这个我做不到,我不能把行放在内存上。我在这里阅读大文件文本。
【解决方案2】:

如果您排除的元素是 String 对象,您可以尝试以下操作:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多