nurnachman
nurnachman

Reputation: 4565

How to disable file lock of a file opened by another app in a Java application

I'm writing a java app that reads a File every second using FileInputStream (it's inside an infinite loop in a seperate thread, that then sleeps for 1 second)

The file is opened in another application.

When I try to save the file in the other application, I get an error message that the file is being used by another program.

I read the FileLock API, and implemented lock and release on writing and reading:

FileOutputStream fos = new FileOutputStream(file);
FileLock fileLock = fos.getChannel().lock();
if (fileLock != null) {
    fos.write(fileContent);
    fileLock.release();
}
fos.close();

How do I disable the file lock on a file that 2 applications are accessing?

Thank you!!

edit: I'm debugging on WINDOWS 7

Upvotes: 2

Views: 2829

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200138

Make sure you always release the lock you have acquired by using the proper try-finally idiom. This is the code I have in production and we have no problems with it on Windows 7:

OutputStream os = openFile();
try {
  if (os.getChannel().tryLock() == null) return;
  ... write to the file ...
}
finally { os.close(); } // this automatically releases the lock

Upvotes: 1

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

That depends on your OS. I think Windows is the only OS that supports locks. Try to download Unlocker. I think there is no pure Java way for achieving this.

Upvotes: 1

Related Questions