0

I want to read nth line from the end of the file. However my file size is very huge like 15MB, so I cannot go through each line to find out the last line. Is there an efficient way to get this nth line ?

I went through RandomAccessFile API however my line sizes are not constant so i was not able to move my file pointer to that nth line location from the end. Can some one help me.

Aditya
  • 532
  • 2
  • 5
  • 14
  • 15MB is not that big. Anyway, since line sizes are variable, you have no choice but to iterate through the whole file, counting newline characters. – Blorgbeard Feb 03 '14 at 02:56

2 Answers2

2

You basically have to read the file backwards. The simplest approach, without using "block" reads, is to the get the length of the file, and then use RandomAccessFile to read bytes at (length--) until you have counted the required number of line feeds / carriage returns. You can then read the bytes forward for one line.

Something like this....

    RandomAccessFile randomAccessFile = new RandomAccessFile("the.log", "r");
    long offset = randomAccessFile.length() - 1;

    int found = 0;
    while (offset > 0 && found < 10) {
        randomAccessFile.seek(offset--);
        if (randomAccessFile.read() == 10) {
            found++;
        }
    }
    System.out.println(randomAccessFile.readLine());

Single byte reads many not be super efficient. If performance becomes a problem, you take the same approach, but read larger blocks of the file (say 8K) at a time, rather than 1 byte at a time.

slipperyseal
  • 2,728
  • 1
  • 13
  • 15
0

Have a look at this answer, which shows that you do need to read through the file (15MB is not big). As long as you are are only storing the latest 9 rows, then you will be able to fly through the file.

Community
  • 1
  • 1
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64