繁体   English   中英

创建锁定文件的Java程序

[英]Creating a Java program that locks a file

如何锁定文件以便用户只能使用我的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) {
    }
  }
}

这是我的示例代码。 它没有给我我想要的东西。 我希望它拒绝一个读取或写入文件的访问权限,直到我使用我的Java程序解锁它。

您可以在要锁定的位置执行此操作:

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

要解锁,您可以这样做:

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

申请之前

检查文件权限是否允许:

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.

对于Unix系统,您必须输入以下代码:

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

您可以使用Java代码以非常简单的方式锁定文件,如:

Process p = Runtime.getRuntime().exec("chmod 755 " + yourfile);

这里exec是一个接受字符串值的函数。 您可以输入任何将执行的命令。

或者你可以用另一种方式做到:

File f = new File("Your file name");
f.setExecutable(false);
f.setWritable(false);
f.setReadable(false);

当然,请检查文件:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM