这是迄今为止发现的最快的版本,比readLines快6倍。在150MB日志文件中,这需要0.35秒,而使用readLines()时为2.40秒。只是为了好玩,linux’wc -l命令需要0.15秒。
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}