javauser35
javauser35

Reputation: 1315

Run exe from Java and "destroy" method of Process

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

Answers (1)

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):

  1. destroy kills the process, as the name itself explains.
  2. In this case it's not needed. Since when the program ends, it's automatically destroyed. But it's not a bad practice to do that (same with scanner and input streams, etcetera).
  3. Again, it's not necessary, but it's a good practice, but it's better to just call the .exe directly.
  4. The same.

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

Related Questions