在这里使用LineNumberReader类来计算和读取文本行可能是一个更好的选择。虽然这不是计算文件中行数的最有效方法(根据这个问题),但对于大多数应用程序来说应该足够了。
从LineNumberReader获取 readLine 方法:
阅读一行文字。每当读取行终止符时,当前行号都会增加。(行终止符通常是换行符 '\n' 或回车符 '\r')。
这意味着当你调用 LineNumberReader 类的 getLineNumber 方法时,它会返回已经被 readLine 方法递增的当前行号。
我在下面的代码中包含了注释来解释它。
System.out.println ("Counting ...");
InputStream stream = ParseTextFile.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
/*
* using a LineNumberReader allows you to get the current
* line number once the end of the file has been reached,
* without having to increment your original 'count' variable.
*/
LineNumberReader br = new LineNumberReader(r);
String line = br.readLine();
// use a long in case you use a large text file
long wordCount = 0;
while (line != null) {
String[] parts = line.split(" ");
wordCount+= parts.length;
line = br.readLine();
}
/* get the current line number; will be the last line
* due to the above loop going to the end of the file.
*/
int lineCount = br.getLineNumber();
System.out.println("words: " + wordCount + " lines: " + lineCount);