How do I get write permissions in the home folder (or the appdata folder, for windows) in Java?

*爱你&永不变心* 提交于 2019-12-10 21:07:07

问题


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.



来源:https://stackoverflow.com/questions/13440993/how-do-i-get-write-permissions-in-the-home-folder-or-the-appdata-folder-for-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!