Buffered Reader readLine() with Empty lines

2019-04-07 16:50发布

I am using buffered reader to grab a line at a time from a text file. I am trying to also get the line number from the text file using a tracking integer. Unfortunately BufferedReader is skipping empty lines (ones with just /n or the carriage return).

Is there a better way to solve this? Would using scanner work?

Example code:

int lineNumber = 0;
while ((s = br.readLine()) != null) {
    this.charSequence.add(s, ++lineNumber);
}

3条回答
看我几分像从前
2楼-- · 2019-04-07 17:34

It must be the FileReader class that skips newline characters then.
I checked the results of readLine() again and it didn't include the new line symbol so it is happening between the two classes FileReader and BufferedReader.

BufferedReader br = null;
String s = null;

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

}
查看更多
你好瞎i
3楼-- · 2019-04-07 17:37

Have you looked at LineNumberReader? Not sure if that will help you.

http://download.oracle.com/javase/6/docs/api/java/io/LineNumberReader.html

查看更多
手持菜刀,她持情操
4楼-- · 2019-04-07 17:42

I could not reproduce your claim that BufferedReader skips empty lines; it should NOT have.

Here are snippets to show that empty lines aren't just skipped.

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

The output for any of the above snippets is:

0001: line1
0002: 
0003: 
0004: line4

Related questions

查看更多
登录 后发表回答