开发者

How to get to the end of a text file in Java efficiently?

开发者 https://www.devze.com 2023-01-27 16:35 出处:网络
I was searching SO to see if there was a question about this but appare开发者_如何学JAVAntly not so. I am currently reading a text file using BufferedReader. My only problem is that I want to read the

I was searching SO to see if there was a question about this but appare开发者_如何学JAVAntly not so. I am currently reading a text file using BufferedReader. My only problem is that I want to read the last line of my file ONLY. IE: I write something to a file 10 times, I want to get the 10th entry. I could easily just run a loop reading each line until I hit my 10th line, but i was wondering if there was a more efficient way since the file is going to keep on increasing and could end up being 100+ entries.

Also, I'd rather not use an external package if possible.

Thanks!


Reading 100 lines is hardly going to be a problem.

It is possible to read a text file backwards, but:

  • Depending on the encoding, it can be very hard. In particular, encodings which have variable widths for different characters, but don't make it obvious where the start of a character is
  • It's really, really ugly code even in good cases. You have to keep skipping backwards in the file, working out where the line starts, etc.

If you want to see just how horrible it is, I've got some code in this Stack Overflow question - it's in C#, but you should be able to understand it reasonably easily. Hopefully it's enough to convince you not to do it.

If you had a file with 100,000 lines it might be worth it... but 100? No way. Just read the whole file.


Perhaps a file is the wrong tool. Where does the text file come from? How about inserting the lines into a database table? Then finding the last row is pretty easy and fast.


The only way to do this is if you knew the length of the file already, which it appears you don't. You'll just have to iterate over it. 100+ lines shouldn't take much longer to loop over than 10 lines. Now if you had a million lines, then you'd probably want to go to a database or something similar.


The class you can use is FileChannel. The problem you will have (in any language) is you don't know where to position in the file to get the last line unless you know the exact length of the line. You can just back up enough to get any reasonable line length and then search forward for it.

0

精彩评论

暂无评论...
验证码 换一张
取 消