开发者

Modifying File while in use using Java

I have this recurrent Java JAR program tasks that tries to modify a file every 60seconds.

Problem is that if user is viewing the file than Java program will not be able to modify the file. I get the typical IOException.

Anyone knows if there is a way in Java to modify a file currently in use? Or anyone knows what would be the best way to solve this problem?

I was thinking of using the File canRead(), canWrite() methods to check if file is in use. If file is in use then I'm thinking of making a backup copy of data that could not be written. Then after 60 seconds add some lo开发者_如何学Gogic to check if backup file is empty or not. If backup file is not empty then add its contents to main file. If empty then just add new data to main file. Of course, the first thing I will always do is check if file is in use.

Thanks for all your ideas.


I was thinking of using the File canRead(), canWrite() methods to check if file is in use.

Not a good idea - you'll run into race conditions e.g. when your code has used those check methods, received true return values, but then the file is locked by a different application (possibly the user) just before you open it for writing.

Instead, try to get a FileLock on the file and use the "backup file" when that fails.


You can hold a lock on the file. This should guarantee you are able to write on the file. See here on how to use the FileLock class.


If the user is viewing the file you should still be able to read it. In this case, make an exact copy of the file, and make changes to the new file.

Then after the next 60 seconds you can either:

1) Check if the file is being viewed and if not, delete it and replace it with the earlier file, then directly update this file.

2) If it is being viewed, continue making changes to the copy of the file.

EDIT: As Michael mentioned, when working with the main file, get a lock on it first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜