Green Onyeji Green Onyeji - 6 months ago 19
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.*;
import java.io.*;

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

You can do this where you want to lock

File f1 = new File(Your file path);
f1.setExecutable(false);
f1.setWritable(false);
f1.setReadable(false);

And For unlock you can just do this

File f1 = new File(Your file path);
f1.setExecutable(true);
f1.setWritable(true);
f1.setReadable(true);

EDIT:

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.

Thanks.