1. 程式人生 > >設定檔案的許可權,阻止使用者訪問(相容Windows和Linux)

設定檔案的許可權,阻止使用者訪問(相容Windows和Linux)

最近的一個專案中需要修改本地檔案的許可權,即對其“加鎖”,使得使用者在解鎖之前不能對其訪問,要求在Windows和Linux下都能執行起來。我們都知道,Linux擁有很嚴格很規範的許可權管理,Linux之所以安全,很大原因也是因為它的許可權管理,因此在Linux下面很好實現這個要求。我使用的是File類提供的setReadable()、setWritable()、setExecutable()幾個方法。然而不幸的是,在windows下使用這幾個方法,最後只有setWritable()成功了,此時的檔案僅僅變成了只讀(但實際我們還是可以看,只是不能修改而已),這樣根本不符合要求。搜尋了好久,最終找到了解決辦法,使用的是dos命令來實現,並藉助 java的封裝特性,將兩個實現方法包裝起來,提供對外的介面,這樣就達到了要求。
下面是程式碼:

import java.io.*;

public class TestLockFile {

    public static void lock(String path) {

            File f = new File(path);
            String osName = System.getProperty("os.name").toLowerCase();
            if(osName.startsWith("win")) {

                try {
                    String com = "cmd /c echo y|cacls "
+ f.getAbsolutePath() + " /t /p everyone:n"; Runtime.getRuntime().exec(com); } catch (Exception e) { e.printStackTrace(); } }else { f.setReadable(false,false); f.setWritable(false,false
); f.setExecutable(false,false); } } public static void unlock(String path) { File f = new File(path); String osName = System.getProperty("os.name").toLowerCase(); if(osName.startsWith("win")) { try { String com = "cmd /c echo y|cacls " + f.getAbsolutePath() + " /t /p everyone:f"; Process p = Runtime.getRuntime().exec(com); //p.waitFor(); } catch (Exception e) { e.printStackTrace(); } }else { f.setReadable(true,false); f.setWritable(true,false); f.setExecutable(true,false); } } public static void main(String[] args) { TestLockFile.lock("F:/test/2.txt"); //TestLockFile.unlock("F:/test/2.txt"); } }