在写入文件时读取文件 [英] Read a file while it's being written
问题描述
我必须读取tomcat日志文件,过了一段时间(例如:一小时)我将再次读取该文件(仅用于新添加的内容),所以我创建了RandomAccessFile来记录我完成的最后一个位置,并使用BufferedReader.readLine()方法。
I have to read the tomcat log file,and after some time(for example:one hour) I will read the file again(just for the new added content),so I create the RandomAccessFile to record the last postion I completed,and use the BufferedReader.readLine() method.
然而,我发现有时我无法读取整个文件行。
However,I found that sometime I can not read the whole line of the file.
例如,tomcat要写下面的内容(仅举例):
For example,the tomcat is tring to write the following content(just example):
192.168.0.0 localhost /index.html .....
192.168.0.0 localhost /index.html .....
此时,我读到的时候可能会得到结果:
And at this moment,when I read I may get the result :
192.168.0 0 localhost /index.html .....
192.168.0 0 localhost /index.html .....
或
192.168.0.0 localhost /index.html .....
192.168.0.0 localhost /index.html .....
这就是说,如果正在编写此行,我的读者会读取不完整的行。
That's to say,my reader read a uncomplete line if this line is being written.
所以我想知道任何想法来决定是否是线阅读已经完成?
So I wonder any idea to decide if the line which is being reading has been completed?
这是核心代码:
raf = new RandomAccessFile(file, "r");
raf.seek(pos);
while ((line = raf.readLine()) != null) {
System.out.println(line);
}
pos = raf.getFilePointer();
raf.close();
我试过这个(添加条件):
I have tried this(add the contidtion):
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();
但它不起作用..
任何想法?
推荐答案
readLine使用换行符。您不能使用它来确定您是否有完整的行。您需要一次读取一个字节并自行解析该行。
readLine consumes the newline character. You can't use it to determine if you have a complete line or not. You need to read one byte at a time and parse the line yourself.
当您获得有效行时,您也不会移动该位置。
Also you are not moving on the position when you get a valid line..
这篇关于在写入文件时读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!