0

I need to execute a batch file from my Java Program. I found multiple threads related to this query. Execute Batch File from Java

In addition to the above information, I need to know if that operation was executed successfully or not. Is it possible to get a handle to that from Java?

Community
  • 1
  • 1
Apps
  • 23
  • 1
  • 3

4 Answers4

3

Both Runtime.exec() and ProcessBuilder.start() return a Process object.

With that, you can use Process.getExitValue(). That said, I don't happen to know if the shell's exit value is the same as the script's.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • I tried that. But I'm getting the following exceptin.Exception in thread "main" java.lang.IllegalThreadStateException: process has not exited at java.lang.ProcessImpl.exitValue(Native Method) at com.mt.test.TestClass2.main(TestClass2.java:13) – Apps Mar 31 '11 at 14:25
  • I think this thread should solve my problem http://stackoverflow.com/questions/2448402/run-bat-file-in-java-and-wait-2 – Apps Mar 31 '11 at 14:28
  • Check out http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Process.html Specifically, the method waitFor(). – DwB Mar 31 '11 at 14:31
2

You should check out When Runtime.exec() won't.

I highly recommend it. It will probably answer your next 4-5 questions.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

Use java.lang.ProcessBuilder to create the call to the batch file. The Process object will allow you to monitor the output and the exit code from the batch file. A non-zero exit code typically indicates failure.

Simon G.
  • 6,587
  • 25
  • 30
  • I think this thread should solve my problem http://stackoverflow.com/questions/2448402/run-bat-file-in-java-and-wait-2 – Apps Apr 01 '11 at 03:23
0

You should really check Commons Exec. It will help you getting the output from the batch file, and setting a timeout, and even creating the command line.

Pablo Grisafi
  • 5,039
  • 1
  • 19
  • 29