With that in mind, meet JumpToLine, a somewhat hackish class I wrote that wraps Apache's Commons I/O LineIterator in a way that lets you seek ahead to a specific line in a file, and is smart enough to remember the last line read (so that you don't read the same line twice).
Example #1
Here's how you might use JumpToLine to seek to line 10 in mylog.log, then read that line and every line after it:
final JumpToLine jtl = new JumpToLine(new File("mylog.log"));
try {
// Open the underlying reader and LineIterator.
jtl.open();
// Seek to line 10; will throw a NoSuchElementException if
// out of range.
jtl.seek(10);
// While there are any lines after and including line 10,
// read them.
while(jtl.hasNext()) {
final String line = jtl.readLine();
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
// Close the underlying reader and LineIterator.
jtl.close();
}Example #2
Here's how you might use JumpToLine to seek to the last line read in mylog.log, and then read any subsequent lines added to the file since it was last read:
final JumpToLine jtl = new JumpToLine(new File("mylog.log"));
try {
// Open the underlying reader and LineIterator.
jtl.open();
// Seek to the last line read since we last tried to
// read any lines from this file.
jtl.seek();
// While there are any more lines to read from the last
// line read position, then read them.
while(jtl.hasNext()) {
final String line = jtl.readLine();
System.out.println(line);
}
// For grins, what is the last line number we read?
System.out.println("Last line number read: " +
jtl.getLastLineRead());
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
// Close the underlying reader and LineIterator.
jtl.close();
}Download JumpToLine here. Note that JumpToLine is dependent on Apache's Commons I/O API which you can download here.



Did you find this post helpful, or at least, interesting?