Is it somehow possible to test if a java.io.File is currently open in another process by any process ? I am using Java 7 and target platforms are Linux/Windows/Mac.
Asked
Active
Viewed 5,015 times
3
-
2Take a look at [this](http://stackoverflow.com/questions/1390592/java-check-if-file-is-already-open) – DonCallisto Feb 16 '12 at 19:06
-
It might help if you told us *why* you need to do this. By mentioning the context of your question you might get a better solution to your overall problem... – thkala Feb 16 '12 at 19:17
-
1- I already have WatchService API in use. But it only triggers events for modify, delete and create. I don't see any possibility to combine these to check if a file is open. I'm currently constructing a distributed document administration tool. The goal is to lock files one user is currently editing, so that other users which share the same files (via MySQL) cannot edit the same file on the same time... FileLock is not platform independent.... – salocinx Feb 16 '12 at 19:51
-
I am not certain that is the way to go - for one you are relying on the assumption that whatever file a user is editing is actually kept open by the editor program until it is closed by the user. On the other hand, if that assumption is valid, you are looking at remote users that would be unable to edit a file for several hours as whoever got to it first does their work. Something like lock contention, only for humans... Your remote users would be forced to work on a local copy of their own to get any work done. – thkala Feb 16 '12 at 20:15
-
You are also forgetting that remote users might want to work off their own local copies of each file as well. You would be better off doing what source code versioning systems do in the case of editing conflicts: have the users manually merge the files. They would have to do it anyway, but now it could happen in a more organized way. Of course, that would depend on the file formats you are interested in sharing. Text files, HTML, XML etc are generally far easier to merge than Microsoft Word documents. – thkala Feb 16 '12 at 20:18
1 Answers
1
There is no easy way in Java to go about this that will work reliably across different platforms. Depending on what you're trying to do, you might be able to patch together a series of try/catch statements which ostensibly work for most cases on most file systems, but you can never have full certainty that the next situation it encounters won't throw it off.
If you do end up going this route you want to ensure that when there is any doubt, it fails fast and doesn't get into a situation where it thinks a file is not open when it really is. My advice would be to see if there is any way you can possibly work around having to do this check.

mandaleeka
- 6,577
- 1
- 27
- 34