缓冲读取器readLine()与空行 [英] Buffered Reader readLine() with Empty lines
问题描述
我正在使用缓冲读卡器从文本文件中一次抓取一行。我也试图使用跟踪整数从文本文件中获取行号。不幸的是, BufferedReader 正在跳过空行(只有 / n 或回车符)。
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?
示例代码:
int lineNumber = 0;
while ((s = br.readLine()) != null) {
this.charSequence.add(s, ++lineNumber);
}
推荐答案
我无法重现您的申请 BufferedReader
跳过空行;它不应该有。
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.
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
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
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
相关问题
- 如何使用扫描仪获取行号 -
LineNumberReader
+扫描仪
组合! - 如何读取每行的字符串行数
- 在Java中,如何从文件中读取特定的行,给定行号?
- 从文本文件中读取特定行
- 使用
java.util.Scanner
验证输入 - 有很多例子 - 做什么这些符号字符串表示:
%02d%01d
? - How to get line number using scanner - a
LineNumberReader
+Scanner
combo! - How to read a string line per line
- In Java, how to read from a file a specific line, given the line number?
- Read a specific line from a text file
- Validating input using
java.util.Scanner
- has many examples - what do these symbolic strings mean:
%02d %01d
?
Related questions
这篇关于缓冲读取器readLine()与空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!