views:

252

answers:

1

I need to be able to mimic 'tail -f' with Java. I'm trying to read a log file as it's being written by another process, but when I open the file to read it, it locks the file and the other process can't write to it anymore. Any help would be greatly appreciated!

Here is the code that I'm using currently:

public void read(){
    Scanner fp = null;
    try{
        fp = new Scanner(new FileReader(this.filename));
        fp.useDelimiter("\n");
    }catch(java.io.FileNotFoundException e){
        System.out.println("java.io.FileNotFoundException e");
    }
    while(true){
        if(fp.hasNext()){
            this.parse(fp.next());
        }           
    }       
}
+1  A: 

Look at the FileChannel API here. For locking the file you can check here

Cshah
You can look at the possible duplicate question in stackoverflow at http://stackoverflow.com/questions/128038/how-can-i-lock-a-file-using-java-if-possible
Cshah
Hmm. I've been looking it over and tried several strategies -- even using java.io.RandomAccessFile in addition to FileChannel, but I still can't manage to let another process write to a file that I'm reading in Java.
rogue780
rogue780 - post the strategies you've tried. Note that if the other process requires an exclusive lock before it writes to the file, then you are pretty much toast (of course, tail wouldn't work in this situation either). But have you tried locking (with a non-exclusive read lock) the top portion of the file?
Kevin Day
The behavior of locks is also specific to the underlying operating system.I havent tried shared locking but i guess you can try that in linux. I doubt whether Windows would support it
Cshah