创建一个Java程序来锁定文件

8

如何锁定文件,使用户只能使用我的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程序将其解锁。

2
你想要并发控制机制吗?还是安全性?我没听懂你的意思。 - Grijesh Chauhan
Java不允许“锁定”文件,因为某些操作系统没有文件锁定机制。如果您想要这样做,您需要使用特定于操作系统的库(并且在*nix上无法工作,因为Unix没有这种类型的文件锁定)。 - Augusto
@augusto,你说我可以使用特定于操作系统的库,我正在使用Windows 7,你能给我一些关于如何开始的指导吗? - Green Onyeji
你所说的“锁定”文件实际上是什么意思?你的问题标题听起来像是你只想防止其他程序读写该文件,但从你所说的内容来看,你真正想要的是某种形式的加密,以便只有你的程序可以解密该文件并使其再次可用? - Andy
我已经更新了我的答案。看一下吧。@GreenOnyeji - TheLittleNaruto
2个回答

16
你可以在你想要锁定的地方这样做:
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");

感谢您的及时回复。但我仍然可以读取文件。我想要的是类似于文件夹锁定的东西,一旦锁定,就拒绝访问该文件夹。但是在这里,我正在尝试对文件执行相同的操作。 - Green Onyeji
非常感谢,我的 file.canRead(); 和 file.canExecute(); 都是 true,而 file.canWrite(); 是 false。有没有办法将所有值都改为 false?同时我会把这个问题标记为已回答。 - Green Onyeji
你好,随时欢迎:) :P :D - TheLittleNaruto

2
您可以使用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());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接