Green Onyeji Green Onyeji - 2 years ago 91
Java Question

creating a java program that locks file

How do I lock a file so that a user can only unlock it using my java program?

import java.nio.channels.*;

public class filelock {

public static void main(String[] args) {

FileLock lock = null;
FileChannel fchannel = null;

try {
File file = new File("c:\\Users\\green\\Desktop\\lock.txt");

fchannel = new RandomAccessFile(file, "rw").getChannel();

lock = fchannel.lock();
} catch (Exception e) {

this is my sample code. It doesn't give me what I want. I want it to deny one access to read or to write the file, until I use my java program to unlock it.

Answer Source

You can do this where you want to lock

File f1 = new File(Your file path);

And For unlock you can just do this

File f1 = new File(Your file path);


Before Applying

Check if the file permission allow :

file.canExecute(); – return true, file is executable; false is not.
file.canWrite(); – return true, file is writable; false is not.
file.canRead(); – return true, file is readable; false is not.

For .nix system you have to put this code

Runtime.getRuntime().exec("chmod 777 file");

Hope this will help you.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download