用Java读取文本文件
我有一个文本文件。我想将内容从一行检索到另一行。 例如,文件可能有 200K 行。我想读取第78行到第2735行的内容。由于文件可能很大,所以我不想将整个内容读入内存。
I have a text file. I would like to retrieve the content from one line to another line.
For example, the file may be 200K lines. I want to read the content from line 78 to line 2735. Since the file may be very large, I do not want to read the whole content into the memory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 BufferedReader.readLine() 并计算行数。您将仅保留缓冲区大小和当前行在内存中。
不,如果不读取到该点的整个文件,就不可能到达第 3412 行(除非您的行都有固定的大小)。
Use BufferedReader.readLine() and count the lines. You'll keep only the buffer size and the current line in memory.
And no, it's not possible to get to line 3412 without reading the whole file up to that point (unless your lines all have a fixed size).
这是一个可能的解决方案的开始:
Here's a start of a possible solution:
只需先逐行阅读并计算行号,然后开始在您提到的行位置获取您需要的内容。
Just simply read line by line first and count the line numbers and start getting the contents you need at the line position you mentioned.
我建议使用 RandomAccessFile,此类使您能够跳转到文件中的特定位置。因此,如果您想读取文件的最后一行,则不必读取前面的所有行,只需跳到该行即可。
I would suggest using a RandomAccessFile, this class enables you to jump to a specific location in a file. So if you want to read the last line of the file you don't have to read all of the previous lines you can just jump to that line.