I have 2-3 programs which can modify file but I want to block others if one program is using it. I cant use synchronization in this. Is there any other provision ?
Asked
Active
Viewed 367 times
1
-
Do you actually mean different programs, or different threads in the same program? – khelwood Nov 24 '16 at 10:17
-
3Does this work for you? http://stackoverflow.com/questions/128038/how-can-i-lock-a-file-using-java-if-possible – Jaydee Nov 24 '16 at 10:18
-
1@Jaydee's suggestion is what I'd normally use. However, the documentation says: "Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified." Make sure this is not a problem for you. – Nando Nov 24 '16 at 10:21
1 Answers
1
The file locking over different application it isn't at Java level handled. You must handle it at OS level. Different OS has different solutions.
I want to block others if one program is using it.
Probably you want to have a write lock, excluding all readers and writers. But allowing some of your programs. At windows maybe present this link interest.
It is very platform dependent, but is a Java code to try it:
FileInputStream in = new FileInputStream(file);
try {
java.nio.channels.FileLock lock = in.getChannel().lock();
try {
Reader reader = new InputStreamReader(in, charset);
...
} finally {
lock.release();
}
} finally {
in.close();
}

matheszabi
- 594
- 5
- 16
-
Actually, there is Java API for it: http://stackoverflow.com/a/128168/718590 – pkalinow Nov 24 '16 at 10:36