【问题标题】:Using the Contains method to filter multiple different lines of an input使用 Contains 方法过滤输入的多个不同行
【发布时间】:2016-05-14 13:52:14
【问题描述】:

我正在使用 bufferedreader 读取包含数据行的 txt 文件。然后我试图根据多个条件过滤掉文本文件的行。在这种情况下,我想跳过以 AA 开头的行和以 DD 开头的行 文本文件看起来像

AA  Data1
BB  Data2
CC  Data3
DD  Data4
AA  Data5
CC  Data6  

到目前为止,我的代码认识到我想跳过这两个,但是,对于从 DD 到 AA 的行,它会跳过 DD 行,但不知道我也想跳过下面的 AA 行所以。所以我的程序输出如下:

BB  Data2
CC  Data3
AA  Data5
CC  Data6 

它根据需要删除了第一个 AA,但留下了第二个 AA,因为它删除了前面行中的 DD。

以下是我当前的代码:

     public static void main(String[] args){

    try {
        BufferedReader br = new BufferedReader(new FileReader("files/txtfile"));
        String line = null;
        String previousLine = null;

        for (line=br.readLine(); line != null;){
            if (previousLine != null) {
                if (line.contains("AA")||line.contains("DD")){
                    previousLine = br.readLine();
                }
                line= br.readLine();
            }
            System.out.println(previousLine);
            previousLine = line;
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}    

任何建议将不胜感激!

【问题讨论】:

    标签: java bufferedreader contains


    【解决方案1】:

    这样做...

    while((line = br.readLine()) != null) {
      if(!(line.contains("AA") || line.contains("DD"))) {
        System.out.println(line);
      }
    }
    

    【讨论】:

    • 想解释一下你的答案吗?
    • 这个仍然只捕获要过滤的第一行,但仍然返回第二行。在我描述的文本文件中,它过滤掉了“DD Data 4”,但在它下面返回了“AA Data5”行。
    • while 将继续读取每一行并将其设置为line,直到达到 null。每次读取一行时,它都会检查它是否不包含 AA 或 DD。如果它不包含任何一个,则打印该行。对其进行了编辑以解决它始终为真的问题。
    【解决方案2】:

    试试这个

    import java.io.*;
    public class tehMain {
        public static void main(String[] args) {
            try( BufferedReader br = new BufferedReader(new FileReader("files/txtfile")) ) {
                for (String line=br.readLine(); line != null; line=br.readLine()) {
                    if (line.contains("AA")||line.contains("DD"))
                        continue;
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      这是你想要的吗?

      for (line=br.readLine(); line != null; line=br.readLine()) {
          if ( !((line.contains("AA")||line.contains("DD")) ) {
              System.out.println(line)
          }
      }
      

      【讨论】:

      • 嗯,尝试这个没有输出,当我停止进程时它给出了退出代码 130
      猜你喜欢
      • 2016-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 2013-08-08
      • 2023-03-31
      相关资源
      最近更新 更多