快速阅读文本文件的最后一行? [英] Quickly read the last line of a text file?
问题描述
在 Java 中从 [非常、非常大] 文件中读取最后一行文本的最快和最有效的方法是什么?
What's the quickest and most efficient way of reading the last line of text from a [very, very large] file in Java?
推荐答案
看看我对 C# 的类似问题.代码将非常相似,尽管 Java 中的编码支持有所不同.
Have a look at my answer to a similar question for C#. The code would be quite similar, although the encoding support is somewhat different in Java.
基本上,这不是一件非常容易的事情.正如 MSalter 指出的那样,UTF-8 确实可以很容易地识别
或
,因为这些字符的 UTF-8 表示与 ASCII 相同,并且这些字节不会出现在多字节字符中.
Basically it's not a terribly easy thing to do in general. As MSalter points out, UTF-8 does make it easy to spot
or
as the UTF-8 representation of those characters is just the same as ASCII, and those bytes won't occur in multi-byte character.
所以基本上,取一个(比如)2K 的缓冲区,并逐渐向后读取(在之前跳到 2K,读取下一个 2K)检查行终止.然后跳到流中的正确位置,在顶部创建一个 InputStreamReader
,并在其顶部创建一个 BufferedReader
.然后只需调用 BufferedReader.readLine()
.
So basically, take a buffer of (say) 2K, and progressively read backwards (skip to 2K before you were before, read the next 2K) checking for a line termination. Then skip to exactly the right place in the stream, create an InputStreamReader
on the top, and a BufferedReader
on top of that. Then just call BufferedReader.readLine()
.
这篇关于快速阅读文本文件的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!