我正在使用缓冲读取器从文本文件中一次抓取一行.我也试图使用跟踪整数从文本文件中获取行号.不幸的是BufferedReader正在跳过空行(只有/ n或回车).
示例代码:
int lineNumber = 0; while ((s = br.readLine()) != null) { this.charSequence.add(s,++lineNumber); }
解决方法
我无法重现你声称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); }
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); }
String text = "line1\n\n\nline4"; Scanner sc = new Scanner(text); int lineNumber = 0; while (sc.hasNextLine()) { System.out.printf("%04d: %s%n",sc.nextLine()); }
0001: line1 0002: 0003: 0004: line4
相关问题
> How to get line number using scanner – LineNumberReader扫描仪组合!
> 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
– 有很多例子
> what do these symbolic strings mean: %02d %01d
?