1

I'm running a Batch file from Java like so:

Runtime
    .getRuntime()
    .exec("cmd /c " + filepath);

Is there any way to find out if the Batch file ran successfully or failed from within Java?

Wiz
  • 38
  • 1
  • 4
  • How about checking the logs? – Stultuske Sep 03 '20 at 12:18
  • Is this a duplicate of https://stackoverflow.com/questions/1410741/how-to-invoke-a-linux-shell-command-from-java – newbie Sep 03 '20 at 12:23
  • That very much depends on your definition of "success". you can of course check the RETURN CODE coming back when executing a command. But is that "enough" ... we dont know, as you didnt specify that part. – GhostCat Sep 03 '20 at 12:24
  • 1
    `exec` returns a [`Process`](https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html), which has an `.exitValue` and a `.getOutputStream` methods you can use to check the exit value and output of the command you executed – Aaron Sep 03 '20 at 12:25

1 Answers1

2

Use the Process instance that Runtime#exec(String) constructs:

Process p = Runtime.getRuntime().exec("cmd /c " + filepath);

You can call Process#waitFor which "causes the current thread to wait, if necessary, until the process represented by this Process object has terminated." Afterwords, see if it completed successfully with Process#exitValue.

You can also interact with the process by fetching its input and output streams:

InputStream inputStream = p.getInputStream(), errorStream = p.getErrorStream();
OutputStream outputStream = p.getOutputStream();
Cardinal System
  • 2,749
  • 3
  • 21
  • 42