I am writing an installer in Java that will accordingly require elevated privileges to access the Program Files directory. Based on information that I\'ve found online, I\'
Okay, I've finally managed to get a solution for this problem that I'm happy with; it's a bit on the ugly side, but it works for what I'm doing.
I borrowed the code from this answer to do the actual privilege elevation; from there, the question was one of actually getting that solution to work with Java. The code for that ends up looking like this:
if (!checkPrivileges()) {
try {
String jarPath = DownloaderMain.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(jarPath, "UTF-8");
decodedPath = decodedPath.substring(1, decodedPath.length());
Elevator.executeAsAdministrator(System.getProperty("java.home") + "\\bin\\java", "-jar " + "\"" + decodedPath + "\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// Run with elevated privileges
}
The checkPrivileges
method is unchanged from above and the Elevator
class is virtually identical to the one that appears in the linked solution (I just took out the unneeded main
method). This solution assumes that the process to be elevated is a jar; it shouldn't be too difficult to change this around to suit your individual needs.
I think that the best approach to achieve this is to use the tools that microsoft built for developers since you can't do it in simple Java. In this case use a manifest file http://msdn.microsoft.com/en-us/library/aa375632(v=vs.85).aspx Just build the wrapper .exe that asks for this privileges and then spawns your java program.