tags:

views:

62

answers:

3

Hi all,

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 logic 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.

+1  A: 

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.

teehoo
Good one.. much simpler than what I had in mind. thanks.
Marquinio
+1  A: 

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.

Artefacto
+2  A: 

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.

Michael Borgwardt
Thanks for all your responses. Now I know what to do.
Marquinio