[英]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.