I am trying to read last n lines of a file in reverse order. Is this the most efficient way to do it? My file is not big but it could eventually grow to several GB. Also, I am trying to read last 10 lines but this one only returns last 9. Anything I am missing?
// Read n lines from the end of the file
public void readFromLast(File file, int lines) {
int readLines = 0;
StringBuilder builder = new StringBuilder();
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "r");
long fileLength = file.length() - 1;
// Set the pointer at the last of the file
randomAccessFile.seek(fileLength);
for (long pointer = fileLength; pointer >= 0; pointer--) {
randomAccessFile.seek(pointer);
char c = (char) randomAccessFile.read();
builder.append(c);
if(c == '\n'){
builder = builder.reverse();
System.out.print(builder.toString());
readLines++;
builder = null;
builder = new StringBuilder();
if (readLines == lines + 1){
break;
}
}
}
} catch (FileNotFoundException e) {
log.info("FileNotFound " +e.getMessage()+ "occured while reading last n lines");
e.printStackTrace();
} catch (IOException e) {
log.info("IOException" + e.getMessage() +" occured while reading last n lines");
} finally {
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
log.info("IOException" + e.getMessage() +" occured while closing the file reading last n lines");
}
}
}
}