How do I get write permissions in the home folder

2019-07-03 12:39发布

问题:

I am trying to save some user settings in the home/appdata folder, but when I use dir.canwrite() it returns false. This is the code I use to determine the home/appdata folder:

public static String getAppDataPath() {
    if (System.getProperty("os.name").contains("Windows")) {
        return System.getenv("APPDATA");
    } else {
        return getUnixHome();
    }
}

public static String getUnixHome() {
    String home = System.getProperty("user.home");
    return home != null ? home : "~";
}

And this is the code trying to mkdir:

public static boolean checkExistenceDir(String path) {
    File dir = new File(path);
    if(!dir.exists()) {
        dir.mkdir();
    }
}

The path in question is:

getAppDataPath() + ".foo" + File.separatorChar

回答1:

You need the Java process to be started as an Administrator.

You can create a run.vbs script in Windows to start your jar:

Set oShell = CreateObject("Shell.Application")
oShell.ShellExecute "cmd.exe", , , "runas", 1
oShell.Run "java -jar myjar.jar"

To make the program always run as administrator, you need it to run as administrator at least once and update a registry key.