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've written an implementation as follows:
public static void main(String args[]) {
if (!checkPrivileges()) { // spawn a copy w/ elevated privileges
Runtime runtime = Runtime.getRuntime();
try {
Process p = runtime.exec(
"runas /profile /user:Administrator \"java -cp . main.Main\"");
} catch (IOException e) { ... }
} else {
// Run with elevated privileges
}
}
The test that I'm using to check for privileges is modified slightly from an answer found here and looks like this:
private static boolean checkPrivileges() {
File testPriv = new File("C:\\Program Files\\");
if (!testPriv.canWrite()) return false;
File fileTest = null;
try {
fileTest = File.createTempFile("test", ".dll", testPriv);
} catch (IOException e) {
return false;
} finally {
if (fileTest != null)
fileTest.delete();
}
return true;
}
When I run this, it fails the privileges test--as expected--and makes the call to exec. Checking if the call worked by looking at p.isAlive()
shows that the process is, in fact, alive; however, I'm not seeing any evidence of the new process and Windows isn't prompting me to grant permissions.
I'm not familiar with using exec()
in Java, so it's quite possible that I've misunderstood its usage somehow. For that matter, is what I'm attempting to do here even possible? If not, is there a straightforward alternative that will actually get me the results that I'm looking for?