How to Wait for windows process to finish before opening file in java

后端 未结 3 719
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 21:51

I have a implemented a listener that notifies if we receive a new file in a particular directory. This is implemented by polling and using a TimerTask. Now the program is s

3条回答
  •  北海茫月
    2021-01-19 22:27

    This one is a bit tricky. It would have been a piece of cake if you could control or at least communicate with the program copying the file but this won't be possible with Windows I guess. I had to deal with a similar problem a while ago with SFU software, I resolved it by looping on trying to open the file for writing until it becomes available.

    To avoid high CPU usage while looping, checking the file can be done at an exponential distribution rate.

    EDIT A possible solution:

    File fileToCopy = File(String pathname);
    int sleepTime = 1000; // Sleep 1 second
    while(!fileToCopy .canWrite()){
        // Cannot write to file, windows still working on it
        Sleep(sleepTime);
        sleepTime *= 2; // Multiply sleep time by 2 (not really exponential but will do the trick)
        if(sleepTime > 30000){ 
            // Set a maximum sleep time to ensure we are not sleeping forever :)
            sleepTime = 30000;
        }
    }
    // Here, we have access to the file, go process it
    processFile(fileToCopy);
    

提交回复
热议问题