如何在java中打开文件之前等待Windows进程完成
我实现了一个监听器,它会通知我们是否在特定目录中收到新文件。这是通过轮询和使用 TimerTask 来实现的。 现在程序的设置是这样的:一旦它收到一个新文件,它就会调用另一个 java 程序来打开该文件并验证它是否是正确的文件。我的问题是,由于轮询发生在指定的秒数后,可能会出现文件被复制到该目录中并因此被 Windows 锁定的情况。
这会引发 IOException,因为尝试打开它进行验证的其他 java 程序不能(“文件正在被另一个进程使用”)。
有没有办法我可以知道Windows何时完成复制,然后调用第二个程序从java进行验证?
如果有人需要代码片段来提供帮助,我将非常乐意发布代码片段。
谢谢
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.
This throws an IOException since the other java program that tries to open it for validation cannot ("File is being used by another process").
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.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
非常感谢您的所有帮助,我在 WatchEvent 上遇到了同样的问题。
不幸的是,正如你所说, file.canRead() 和 file.canWrite() 都返回 true,即使文件仍然被 Windows 锁定。所以我发现,如果我尝试用相同的名称“重命名”它,我就知道 Windows 是否正在处理它。这就是我所做的:
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:
这个有点棘手。如果您可以控制或至少与复制文件的程序进行通信,那将是小菜一碟,但我想这在 Windows 中是不可能的。不久前我不得不使用 SFU 软件处理类似的问题,我通过循环解决了它尝试打开文件进行写入,直到该文件可用。
为了避免循环时 CPU 使用率过高,可以按指数分布速率检查文件。
编辑一个可能的解决方案:
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
对象,然后使用canRead
或canWrite
来知道文件是否准备好被其他java程序使用。http://docs.oracle.com/javase/6 /docs/api/java/io/File.html
其他选项是尝试在第一个程序上打开文件,如果它抛出异常,则不要调用其他 java 程序。但我会推荐上面的
'File
选项。I think you can create the
File
object and then usecanRead
orcanWrite
to know whether file ready to be used by the other java program.http://docs.oracle.com/javase/6/docs/api/java/io/File.html
Other option is to try to Open file on first program and if it throws the exception then dont call the other java program. But I ll recommend the above
'File
option.