Question

I'm trying to create a method which just polls a text file in a particular directory. If the text file changes size it reads the most recent entry made to it. I believe I have to use threading to do this?

so far I have:

public boolean FileUpdated(File file) {
    this.timeStamp = file.lastModified();

    if (this.timeStamp != timeStamp) {
        this.timeStamp = timeStamp;
        //file is updated
        return true;
    }
    //file is not updated
    return false;
}

Can anyone point me in the right direction please?

Was it helpful?

Solution

You are correct in your assumption that a separate thread will be required for the pooling activity, However rather then using a standard thread it may be best to use a Timer Thread as this will implicitly take care of scheduling your 'FileUpdated" methods at regular intervals. In order for this to work you would also need to place or call your FileUpdated method from a TimerTask for example:

public class FileChecker {
Timer timer;

public FileChecker(int seconds,File aFileToCheck) {
    
    timer = new Timer();
    timer.schedule(new FileCheckTask(aFileToCheck),0,seconds*1000);
 
}




class FileCheckTask extends TimerTask {

private File fileToCheck;

public FileCheckTask(File aFileToCheck){

    
      fileToCheck = aFileToCheck;
}
    
    public void run() {
        System.out.format("Checking File....");
        
        FileUpdated(fileToCheck);
    }


public void FileUpdated(File file) {

this.timeStamp = file.lastModified();

if (this.timeStamp != timeStamp) {
    this.timeStamp = timeStamp;
    
   //file is updated, do something here
    
}

}

}

public static void main(String args[]) {
    //checks file every 5 seconds
    new FileChecker(5,"PathToTargetFile");
   
}

}

You will note that I have changed your methods return type to void as you obviously cannot return a value from within the context of the TimerTask "run" method, instead you will simply check the condition and then do any work you need to do, for example reading the updated file, in the TimerTask thread itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top