2

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.

Community
  • 1
  • 1
Abhishek_Mishra
  • 4,551
  • 4
  • 25
  • 38

3 Answers3

3

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.

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
3

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

Haseena
  • 484
  • 2
  • 11
  • 25
0

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216