Search code examples
javaconcurrencyiorandom-access

Read a file while it's being written


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?


Solution

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