Reputation: 1315
I need to run exe from my java application.So I wrote a .bat file and I call it from my java app. Batch file runs the exe.
Here it is:
String command = "C:\\Users\\XXXX\\Desktop\\DenemeBat\\hadi.bat";
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", command);
pb.redirectErrorStream(true);
Process p = pb.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
int excode=p.waitFor();
But there can be different ways to call exe from java.For example.
Case:1
String command = "C:\\Users\\XXXX\\Desktop\\DenemeBat\\hadi.bat";
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", command);
pb.redirectErrorStream(true);
Process p = pb.start();
Case:2 There is no cmd here.Direct link to .bat file.
String command = "C:\\Users\\XXXX\\Desktop\\DenemeBat\\hadi.bat";
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
Case:3 And here there is no .bat file and cmd.Directly run the exe.
String command = "C:\\Users\\XXXX\\Desktop\\DenemeBat\\tryabc.exe";
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
So which way is better.And my real question is that is it necessary to destroy the process.
I use waitfor method and it returns 0 if the code works well.
Question 1:What is the correct way to kill the process?
Question 2:Is it necessary to kill process.If I don't kill what happens?
Question 3:If I use .bat file need I kill the process?
Question 4:If I don't use .bat,cmd and directly run the exe is it necessary to kill the process?
And lastly what is difference between waitfor and destroy methods?Is waitfor method also destroy the process?
Upvotes: 0
Views: 588
Reputation: 753
In your case the best solution would be to simply call your executable by using ProcessBuilder with .exe path as the command.
Regarding your questions (according to java 7 doc):
destroy
kills the process, as the name itself explains.Difference between WaitFor and Destroy: WaitFor basically makes the thread which executes the program to wait until it finishes whereas destroy finishes the process.
Upvotes: 1