The shortcut you see in your desktop is actually a file with the extension .lnk
. It's real full path is, then:
C:\Users\Desktop\notepad.exe.lnk
Trying to run it through exec()
will yield a "CreateProcess error ... is not a valid Win32 application" error.
Fortunately, you can run those as well through the ProcessBuilder
utility class.
public static void main(String[] args) throws Exception {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c",
"C:\\Users\\robert\\Desktop\\notepad.lnk");
Process p = pb.start();
p.waitFor();
}
If you must use Runtime.getRuntime().exec()
, you can open the lnk
file through rundll32
:
Process p = Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL " +
"C:\\Users\\robert\\Desktop\\notepad.lnk");
p.waitFor(); // watch out
But keep in mind, by this approach, the p.waitFor();
and similar method calls may not have the expected result: As you can see, the created process is the rundll32
, not the shortcut's (notepad.exe
).