Possible Duplicate:
Read a specific line from a text file
Is there any way to read a line in a file in java.I mean if i want to read 100th line only then can i read it directly? Or I have to read the whole file until it comes to line 100.
Possible Duplicate:
Read a specific line from a text file
Is there any way to read a line in a file in java.I mean if i want to read 100th line only then can i read it directly? Or I have to read the whole file until it comes to line 100.
No, no matter the abstractions, there really isn't an efficient way of "directly" reading the 100th line from a file-system. You can of course use offsets in case you have lines with fixed lengths per line (assuming CR or LF etc.) but that's it. You can't jump around in a file based on the "line" abstraction.
You can use java.io.RandomAccessFile.
Moving to 100th line use the following lines:
RandomAccessFile file = new RandomAccessFile("D:\\test.txt", "rw");
int totalLines = (int)file.length();
file.seek(100);
long pointer = file.getFilePointer();
for(int pt = 100; ct < totalLines; ct++){
byte b = file.readByte(); //read byte from the file
System.out.print((char)b); //convert byte into char
}
file.close();
For more details please see the below link which will helps you: http://tutorials.jenkov.com/java-io/randomaccessfile.html
Under most circumstances you will need to read line-by-line starting from the start of the file.
There are exceptions to this:
If you create and maintain an index for the file that indicates the positions of each line start, you can lookup a line in the index and then seek
the file to the position to read it.
If your file consists of fixed length lines, you can calculate the position of the start of a line as line_no * line_length
, and then seek
to that position.