写了一个读文件最后一行的算法,主要思想是利用RandomAccessFile 这个类一开始先将文件的游标移动到文件最后一个字符,然后逐渐向文件头推进,一旦找到'/r'或者‘/n’的时候就将当前的游标记录下来,这个游标的位置就是文件最后一行的起始位置。
这个方法的优点是在处理大文件的时候,效率会高一些。
/**
* 打印文件的最后n行内容
* @param monitorFile
* @param n
* @param lineProcess
*/
private void readLastNLine(File monitorFile, int n, IProcessLine lineProcess) {
RandomAccessFile randomAccess = null;
try {
randomAccess = new RandomAccessFile(monitorFile, "r");
// boolean eol = false;
// int c = -1;
long fileLength = randomAccess.length();
long size = 1;
boolean hasEncountReturn = false;
ww: while (true) {
long offset = fileLength - (size++);
if (offset < 0) {
break ww;
}
randomAccess.seek(offset);
switch (// c =
randomAccess.read()) {
case '\n':
case '\r':
if (!hasEncountReturn && (n--) <= 0) {
randomAccess.seek(offset + 1);
break ww;
}
hasEncountReturn = true;
continue;
default:
hasEncountReturn = false;
}
}
String line = null;
while ((line = randomAccess.readLine()) != null) {
// listener.handle(line);
lineProcess.print(line);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(randomAccess);
}
}
private interface IProcessLine {
void print(String line);
}