【问题标题】:BufferedReader() returning empty string when there are more strings in the file?当文件中有更多字符串时,BufferedReader() 返回空字符串?
【发布时间】:2013-03-20 03:08:29
【问题描述】:

我的 txt 文件如下所示:

data;data2;data3;data4..........up till data3146

当我在记事本中打开 txt 文件时,我会以上面给出的形式看到它。 但是当我将前几行复制粘贴到另一个地方时,有一个 1 行间隙 b/w data1 和其他所有内容。因此,我在访问 Java 中的文件并在循环中使用带有缓冲读取器的数据时遇到问题。我该如何纠正?我无法删除空行,因为它甚至在原始文件中都不可见。

【问题讨论】:

  • 尝试在 Notepad++ 中打开它;)
    (可能您必须启用显示隐藏字符)
  • 如需尽快获得更好的帮助,请发帖SSCCE

标签: java file-io bufferedreader


【解决方案1】:

您可以忽略空白行。像这样 -

    while ((line = reader.readLine()) != null) {
        if(line.trim().isEmpty()) {
            continue;
        }
        ...   

【讨论】:

    【解决方案2】:

    你可以试试这个方法:

    BufferedReader reader = new BufferedReader(new FileReader(new File("your file path")));
        String str = null;
        while((str = reader.readLine())!=null) {
            if (str.matches("[' ']+")) {
                continue;
            } else {
                // to do 
            }
        }
    

    【讨论】:

    • 您不需要在continuebreakreturnthrow 之后添加else
    【解决方案3】:

    我认为问题出在行尾。基本上你可以跳过空行:

    String line;
    while ((line = reader.readLine()) != null) {
      if ("".equals(line.trim()) {
        continue;
      }
      // do your stuff here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 2022-10-26
      • 1970-01-01
      相关资源
      最近更新 更多