从日志文件 XXX.log 最后一个字符开始往前查询
条件:根据关键字 “warning” 去查询
代码复制即用,只需修改要查询的文件路径(filePath)和条件关键字(warning)改成自己的即可:
public class TTT {
public static void main(String[] args) {
RandomAccessFile rf = null;
try {
String filePath = "C:\\Users\\admin\\Desktop\\test.log";
rf = new RandomAccessFile(filePath, "r");
long len = rf.length();
long start = rf.getFilePointer();
long nextend = start + len - 1;
String line;
rf.seek(nextend);
int c = -1;
while (nextend > start) {
c = rf.read();
if (c == '\n' || c == '\r') {
line = rf.readLine();
if (line != null && line.contains("warning")) {
String s = new String(line.getBytes("ISO-8859-1"), "UTF-8");
System.out.println(s);
}
nextend--;
}
nextend--;
rf.seek(nextend);
if (nextend <= start) {
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (rf != null)
rf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行后的结果:
我的log文件截图:
|