【发布时间】:2010-12-16 11:21:58
【问题描述】:
我必须读取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();
但它不起作用..
有什么想法吗?
【问题讨论】:
-
也许总是跳过最后一行?
标签: java concurrency io random-access