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

后端 未结 3 722
伪装坚强ぢ
伪装坚强ぢ 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:15

    Thanks a lot for all the help, I was having the same problem with WatchEvent. Unfortunately, as you said, file.canRead() and file.canWrite() both return true, even if the file still locked by Windows. So I discovered that if I try to "rename" it with the same name, I know if Windows is working on it or not. So this is what I did:

        while(!sourceFile.renameTo(sourceFile)) {
            // Cannot read from file, windows still working on it.
            Thread.sleep(10);
        }
    

提交回复
热议问题