如何在java中打开文件之前等待windows进程完成 [英] How to Wait for windows process to finish before opening file in java

查看:135
本文介绍了如何在java中打开文件之前等待windows进程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一个侦听器,它通知我们是否在特定目录中收到新文件。这是通过轮询和使用TimerTask实现的。
现在程序已设置好,一旦收到新文件,它就会调用另一个打开文件的java程序,并验证它是否是正确的文件。我的问题是,由于轮询在指定的秒数后发生,可能会出现在该目录中复制文件并因此被Windows锁定的情况。

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 so set up that once it receives a new file it calls another java program that opens the file and validates whether it is the correct file. My problem is that since the polling happens a specified number of seconds later there can arise a case in which a file is being copied in that directory and hence is locked by windows.

这会引发IOException,因为尝试打开它进行验证的其他java程序不能(File正被另一个进程使用)。

This throws an IOException since the other java program that tries to open it for validation cannot ("File is being used by another process").

有没有办法让我知道Windows何时完成复制,然后调用第二个程序从java进行验证?

Is there a way I can know when windows has finished copying and then call the second program to do the validations from java?

如果有人需要它们以帮助我,我将非常乐意发布代码片段。

I will be more than happy to post code snippets if someone needs them in order to help.

谢谢

推荐答案

这个有点棘手。如果你可以控制或至少与复制文件的程序进行通信,那将是一块蛋糕,但我认为这是不可能的。我不得不用 SFU 软件处理类似问题,我通过循环解决了这个问题尝试打开文件进行写入,直到可用。

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.

为避免循环时CPU使用率过高,可以在指数分布率。

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

编辑可能的解决方案:

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);

这篇关于如何在java中打开文件之前等待windows进程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆