Reputation: 107
I have this part of code, supposed to start msg.exe subprocess on Windows:
ProcessBuilder pb = new ProcessBuilder("msg.exe");
try {
proc = pb.start();
} catch (IOException ex) {
jLabel4.setText("Cannot launch message box process");
return;
}
Now I tried to delete/rename msg.exe and no exception thrown: both lines in catch clause aren't executed. How can I detect if file not found for execution by process builder?
If I try to catch FileNotFoundException, it says this one is already caught (probably as a part of IOException). If I try to catch only FileNotFoundException, it requires to catch IOException with warning.
Upvotes: 1
Views: 860
Reputation: 8250
My shot in the dark:
You have an executable named "msg.exe" in the directory of your Java application which you are trying to execute from your Java code. When renaming or deleting the file, you are expecting new ProcessBuilder("msg.exe").start()
to throw an IOException
.
This will not happen since if there is no file called "msg.exe" in the directory, then it will search for it in your %PATH%
, and finally find it in C:\Windows\System32\
, which is probably what you did not intend.
This dilemma can be solved by explicitly stating that the file you are trying to execute must exist in the current directory: new ProcessBuilder("./msg.exe")
Upvotes: 1
Reputation: 7720
Your code will not throw FileNotFoundException
, it will throw IOException
See the Documentation
Below is the exception I got , As I am on linux so there is no need to change the name of msg.exe
to some other to generate exception
java.io.IOException: Cannot run program "msg.exe": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at Neeraj.main(Neeraj.java:8)
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:187)
at java.lang.ProcessImpl.start(ProcessImpl.java:134)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 1 more
Upvotes: 0
Reputation: 61
The start() method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes.Each process builder manages these process attributes
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("msg.exe");
// pb.directory(new File("c:\\xyzwsdemo"));
try {
Process proc = pb.start();
} catch (IOException ex) {
System.out.println("Cannot launch message box process");
return;
}
}
executed the above class : No error
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("msfg.exe");
// pb.directory(new File("c:\\xyzwsdemo"));
try {
Process proc = pb.start();
} catch (IOException ex) {
System.out.println("Cannot launch message box process");
return;
}
}
Rename msg.exe to msfg.exe -Exception caught, same after deleting the code
Did you try executing in main class and check again?
Upvotes: 0