BufferedReader的readLine()方法如何处理空行?

5
我正在使用缓冲读取器从文本文件中逐行获取文本。我还尝试通过跟踪整数来获取文本文件中的行号。不幸的是,BufferedReader会跳过空行(只有/n或回车符的行)。
是否有更好的解决方法?使用扫描器是否可行?
示例代码:
int lineNumber = 0;
while ((s = br.readLine()) != null) {
    this.charSequence.add(s, ++lineNumber);
}

你的变量s声明是什么? - RageD
1
在未来的“它不起作用”的问题中,一个SSCCE风格的代码片段会非常有帮助。 - BalusC
3个回答

22

我无法重现您所声称的BufferedReader跳过空行的情况;它不应该这样做。

下面是代码片段,以展示空行并没有被跳过。

java.io.BufferedReader

    String text = "line1\n\n\nline4";
    BufferedReader br = new BufferedReader(new StringReader(text));
    String line;
    int lineNumber = 0;
    while ((line = br.readLine()) != null) {
        System.out.printf("%04d: %s%n", ++lineNumber, line);
    }

java.io.LineNumberReader

    String text = "line1\n\n\nline4";
    LineNumberReader lnr = new LineNumberReader(new StringReader(text));
    String line;
    while ((line = lnr.readLine()) != null) {
        System.out.printf("%04d: %s%n", lnr.getLineNumber(), line);
    }

java.util.Scanner

    String text = "line1\n\n\nline4";
    Scanner sc = new Scanner(text);
    int lineNumber = 0;
    while (sc.hasNextLine()) {
        System.out.printf("%04d: %s%n", ++lineNumber, sc.nextLine());
    }

任何一个以上代码段的输出结果均为:

0001: line1
0002: 
0003: 
0004: line4

相关问题


1
糟糕,我的错。找到了问题代码。谢谢大家,抱歉提出了这样的低质量问题,应该更深入地研究一下。当时真的被难住了。 - Walt
看起来我试图将这些行添加到列表中,但它没有保留回车符。String s = null;this.charSequence = new LinkedList<String>(); while ((s = br.readLine()) != null) { this.charSequence.add(s); } - Walt

3
一定是FileReader类跳过了换行符。
我再次检查了readLine()的结果,它不包括换行符,因此这种情况发生在FileReader和BufferedReader这两个类之间。
BufferedReader br = null;
String s = null;

try {
    br = new BufferedReader(new FileReader(fileName));
    while ((s = br.readLine()) != null) {
        this.charSequence.add(s);
    }
} catch (...) {

}

Java的API说:readLinepublic String readLine() throws IOException 读取一行文本。一行被认为是以换行符('\n'),回车符('\r')或回车符后紧接着的换行符之一终止的。 返回: 一个包含该行内容的字符串,不包括任何行终止字符,如果已到达流的末尾,则返回null 抛出: IOException - 如果发生I/O错误 - Walt

3

这是正确的。根据文档,LineNumberReader的readLine()行为如下:“读取一行文本。每当读取到一行终止符时,当前行号将递增。” - Wildcat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接