我必须阅读tomcat日志文件,一段时间后(例如:一个小时)我会再次阅读该文件(仅针对新添加的内容),所以我创建了RandomAccessFile来记录我完成的最后一个位置,并使用BufferedReader.readLine() 方法。
但是,我发现有时我无法读取文件的整行。
例如,tomcat 正在尝试编写以下内容(仅示例):
192.168.0.0 本地主机 /index.html .....
此刻,当我阅读时,我可能会得到结果:
192.168.0 0 本地主机 /index.html .....
或者
192.168.0.0 本地主机 /index.html .....
也就是说,如果正在写这行,我的读者会读到一个不完整的行。
所以我想知道确定正在阅读的行是否已经完成?
这是核心代码:
raf = new RandomAccessFile(file, "r");
raf.seek(pos);
while ((line = raf.readLine()) != null) {
System.out.println(line);
}
pos = raf.getFilePointer();
raf.close();
我试过这个(添加条件):
raf = new RandomAccessFile(file, "r");
raf.seek(pos);
while ((line = raf.readLine()) != null) {
if(line.chartAt(line.length()-1)=='\n'){
System.out.println(line);
} else
raf.seek(pos); //roll back to the last position
}
pos = raf.getFilePointer();
raf.close();
但它不起作用..
任何想法?