我想在Java中获取普通文本文件的最后一行时感到困惑。我该如何做?而且如果不使用scanner,哪种方法是最好的?
谢谢
最简单的方法是遍历文件中的每一行,当到达文件末尾时停止。例如:
// I assume this is disposed properly etc
private static String getLastLine(BufferedReader reader) throws IOException {
String line = null;
String nextLine;
while ((nextLine = reader.readLine()) != null) {
line = nextLine;
}
return line;
}
对于空的读取器,这将返回null。
除非我知道我要读一个真的很大的文件,否则我会这么做。尝试直接跳转到最后一行是困难的。真的很困难,特别是如果你需要一个可变宽度编码,如UTF-8。