【问题标题】:Why does isEmpty() skip many lines in BufferedReader?为什么 isEmpty() 在 BufferedReader 中会跳过很多行?
【发布时间】:2012-05-23 21:04:39
【问题描述】:

我正在尝试使用 BufferedReader 从文本文件中读取数据。我想跳过带有“#”和“*”的行,它可以工作。但它不适用于空行。我使用 line.isEmpty() 但只显示第一个输出。

我的文本文件如下所示:

# Something something
# Something something


# Staff No. 0

*  0  0  1

1 1 1 1 1 1

*  0  1  1

1 1 1 1 1 1

*  0  2  1

1 1 1 1 1 1

我的代码:

StringBuilder contents = new StringBuilder();
    try {
      BufferedReader input =  new BufferedReader(new FileReader(folder));
      try {
        String line = null;
        while (( line = input.readLine()) != null){
          if (line.startsWith("#")) {
              input.readLine(); 
          }
          else if (line.startsWith("*")) {
              input.readLine(); 
          }
          else if (line.isEmpty()) { //*this
              input.readLine(); 
          }
          else {
          contents.append(line);
          contents.append(System.getProperty("line.separator"));
          System.out.println(line);
          }
        }
      }
      finally {
        input.close();
      }
    }
    catch (IOException ex){
      ex.printStackTrace();
    }

我想要的输出应该是这样的:

1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1

【问题讨论】:

    标签: java text io readline bufferedreader


    【解决方案1】:

    看看你的代码的流控制。

    当你这样做时,你会在哪里结束?

    else if (line.isEmpty()) { //*this
        input.readLine(); 
    }
    

    你读了一行,代码继续循环:

    while (( line = input.readLine()) != null){
    

    阅读另一行。

    所以每次遇到空行时,都会忽略它后面的行。

    你可能应该这样做:

    else if (line.isEmpty()) { //*this
      continue;
    }
    

    【讨论】:

      【解决方案2】:

      如果没有分配给变量,每次对readline() 的调用都会跳过一行,只需删除这些调用,因为这会清空大部分 if-else 块,您可以将其简化为:

      // to be a bit more efficient
      String separator = System.getProperty("line.separator");
      while (( line = input.readLine()) != null)
      {
          if (!(line.startsWith("#") || 
                line.startsWith("*") ||
                line.isEmpty() )) 
          {
              contents.append(line);
              contents.append(separator);
              System.out.println(line);
          }
      }
      

      【讨论】:

      • 谢谢先生。这对我很有帮助。
      猜你喜欢
      • 2019-11-16
      • 2023-03-15
      • 2015-02-26
      • 2014-06-07
      • 1970-01-01
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      相关资源
      最近更新 更多