Read a file while it's being written

2020-04-23 05:08发布

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.

For example,the tomcat is tring to write the following content(just example):

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 .....

or

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?

This is the core code:

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();

But it does not work..

ANy idea?

2条回答
Juvenile、少年°
2楼-- · 2020-04-23 05:50

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..

查看更多
趁早两清
3楼-- · 2020-04-23 05:55

readLine() strips EOL characters so you don't see it. There is no difference between EOF and EOL from its point of view which is troubling in your case. In addition to Peter's solution, you can try seeking one byte back after you read the line and check if it was EOL or not. Be careful about line ending style being used, though.

查看更多
登录 后发表回答