[英]Creating a Java program that locks a file
How do I lock a file so that a user can only unlock it using my Java program? 如何锁定文件以便用户只能使用我的Java程序解锁它?
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.
我希望它拒绝一个读取或写入文件的访问权限,直到我使用我的Java程序解锁它。
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);
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 a Unix system you have to put in this code: 对于Unix系统,您必须输入以下代码:
Runtime.getRuntime().exec("chmod 777 file");
You can lock the file by using Java code in a very simple way like: 您可以使用Java代码以非常简单的方式锁定文件,如:
Process p = Runtime.getRuntime().exec("chmod 755 " + yourfile);
Here exec is a function which accepts a string value. 这里exec是一个接受字符串值的函数。 You can put any command in that it will execute.
您可以输入任何将执行的命令。
Or you can do it with another way like: 或者你可以用另一种方式做到:
File f = new File("Your file name");
f.setExecutable(false);
f.setWritable(false);
f.setReadable(false);
To be sure, check the file: 当然,请检查文件:
System.out.println("Is Execute allow: " + f.canExecute());
System.out.println("Is Write allow: " + f.canWrite());
System.out.println("Is Read allow: " + f.canRead());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.