Reading a specific line from a text file in Java

2019-01-05 05:05发布

Is there any method to read a specific line from a text file ? In the API or Apache Commons. Something like :

String readLine(File file, int lineNumber)

I agree it's trivial to implement, but it's not very efficient specially if the file is very big.

9条回答
一纸荒年 Trace。
2楼-- · 2019-01-05 05:41

Because files are byte and not line orientated - any general solutions complexity will be O(n) at best with n being the files size in bytes. You have to scan the whole file and count the line delimiters until you know which part of the file you want to read.

查看更多
We Are One
3楼-- · 2019-01-05 05:46

If you are going to work with the same file in the same way (looking for a text at certain line) you can index your file. Line number -> offset.

查看更多
做自己的国王
4楼-- · 2019-01-05 05:51

According to this answer, Java 8 enables us to extract specific lines from a file. Examples are provided in that answer.

查看更多
登录 后发表回答