0

How can I lock the file in JVM in such way that other non JVM processes can't get access for write access? I need to read the file and while reading I want to be sure that other processes do not modify the file. I tried creating FileInputStream and it does lock the file for deleting but it doesn't prohibit the modification of file.

I also tried RandomAccessFile:

RandomAccessFile raf = new RandomAccessFile(file, "rw");
InputStream is = Channels.newInputStream(raf.getChannel());

but it also doesn't prevent modifications.

PS: Further in the code I need InputStream

maks
  • 5,911
  • 17
  • 79
  • 123
  • possible duplicate of [How can I lock a file using java (if possible)](http://stackoverflow.com/questions/128038/how-can-i-lock-a-file-using-java-if-possible) – Justin Oct 15 '14 at 11:11
  • That code doesn't work. I can't acquire lock on stream that is open for reading. I get `java.nio.channels.NonWritableChannelException` – maks Oct 15 '14 at 11:18
  • @maks there is more than one answer on the duplicate page. – Kenster Oct 15 '14 at 12:05
  • @Kenster but they all are about locking InputStream or RandomAccessFile. Answer regarding using synchrinized block I don't take into account – maks Oct 15 '14 at 13:50
  • If the point of your question is how to block other processes from modifying the file, this is OS-dependent. On Unix, for example, file locks are cooperative. A process will only honor a lock if it's written specifically to do so. – Kenster Oct 15 '14 at 14:28

2 Answers2

2

Unfortunately, this is not something Java can do - perhaps largely because it is supported in different ways on different platforms and Java needs to maintain cross platform compatibility.

I assume, from your question for example, that you are on Windows as under Linux the above code would not even prevent file deletion.

There is some detailed information on file locking at http://en.wikipedia.org/wiki/File_locking which explains the issue.

BarrySW19
  • 3,759
  • 12
  • 26
-1

Have you tried to use FileLock? The usage will be like this snippet:

FileInputStream in = new FileInputStream(file);
try {
    java.nio.channels.FileLock lock = in.getChannel().lock();
    try {
        Reader reader = new InputStreamReader(in, charset);
        //Other actions...
    } finally {
        lock.release();
    }
} finally {
    in.close();
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254