Is there any way that I can open notepad or other application from shortcuts?
Here is my code:
import java.io.File;
import java.io.IOException;
public class acrobat {
public static void main(String[] args) throws IOException, InterruptedException {
String[] notepad = {"C:\\Users\\Desktop\\notepad.lnk"};
Process p = Runtime.getRuntime().exec(notepad);
p.waitFor();
}
}
I want to open application from shortcut, but I am getting error..
Exception in thread "main" java.io.IOException: Cannot run program "C:\Users\robert\Desktop\notepad.lnk": CreateProcess error=193, %1 is not a valid Win32 application
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at acrobat.main(acrobat.java:11)
Caused by: java.io.IOException: CreateProcess error=193, %1 is not a valid Win32 application
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 4 more
If I only write notepad.exe than its working but, with path its not working. Is there any way that I can open with shortcuts?
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
).
Look at Desktop.open(File)
and associated methods.
However, if you really must open links..
Read (and implement) all the recommendations of When Runtime.exec() won't. That might solve the problem. If not, it should provide more information as to the reason it failed. Then ignore that it refers to exec
and build the Process
using a ProcessBuilder
. Also break a String arg
into String[] args
to account for arguments which themselves contain spaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With