How can I read a text file starting at X number line? I can start reading the file and do nothing until X line is reached but I'm wondering if theres a better way to do it.
Asked
Active
Viewed 184 times
2
-
I'm not sure it's possible to open a stream midway into a file. Anything wrong with eating the first `X - 1` lines? – Tim Biegeleisen Sep 13 '15 at 05:37
2 Answers
1
In general you cannot do this unless you have a pre-built index of line lengths or line lengths in your file are known to be fixed. You can skip given number of bytes when reading random access file, but in order to skip given number of lines you should count the line-break symbols (like \n
). The file system does not store the line break positions anywhere.

Tagir Valeev
- 97,161
- 19
- 222
- 334
0
What you are looking for is RandomAccessFile. You can use it like the example below. But you need to know the position that you want to read. I am sure you can play with it a little bit and find how to use it.
private static byte[] readFromFile(String filePath, int position, int size) throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
More info: http://www.tutorialspoint.com/java/io/java_io_randomaccessfile.htm
http://examples.javacodegeeks.com/core-java/io/randomaccessfile/java-randomaccessfile-example/

shan1024
- 1,389
- 7
- 17