Kalrav J Parsana Kalrav J Parsana - 11 days ago 6
Java Question

Java : How to block other program from accessing file if one program is using it?

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 ?

Answer

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();
}