5

I have a desktop java application that uses Swing as a GUI library. There is an installer that I have to install inside this application, but it must have administrative privileges.

I am using

Process p = Runtime.getRuntime().exec(pathToTheExeInstaller);

to install the program. But it has this error when running it without administrator privilege:

error

Is there a way to get Run as administrator in the context menu (the right click menu) in the generated jar file when clean and build is used in NetBeans:

enter image description here

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
Tarek
  • 1,904
  • 2
  • 18
  • 36

2 Answers2

3

This is what you need,

Runtime.getRuntime().exec("powershell.exe Start-Process 'pathToTheExeInstaller' -verb RunAs");

This will give a prompt to the user asking permissions to get elevated access for your installer.

Extracted from this answer


Example

Runtime.getRuntime().exec("powershell.exe Start-Process 'notepad.exe' -verb RunAs");

enter image description here

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
  • I tried this, it gives an error with the arguments, the path contains spaces, so I put "", still gives an error. – Tarek Aug 05 '18 at 09:16
  • I did, but the problem is that the path has `~1` in it, it what `createTempDirectory` returns. – Tarek Aug 05 '18 at 09:28
  • I'm getting this error: `Start-Process : This command cannot be run due to the error: The system cannot find the file specified. At line:1 char:1 + Start-Process C:\Users\TAREQK~1\AppData\Local\Temp\NSIS Installer7238 ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand` – Tarek Aug 05 '18 at 09:28
  • @Tarek I've edited the answer, check it now. Use `'` instead of `"`. – Roshana Pitigala Aug 05 '18 at 09:29
  • yeah sorry I forgot. – Tarek Aug 05 '18 at 11:33
  • I assume this only work on windows, is there a solution that works on any platform ? – BHA Bilel Jun 08 '21 at 02:01
0

Right-click on the "command prompt" and choose "run as administrator", then you can

java -jar myprogram.jar
HadiMa
  • 1
  • 1