Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the return code in Java after executing a windows command line command

Tags:

java

I'm doing something like this in Java right now

Process p = Runtime.getRuntime().exec("ping -n 1 -w 100 127.0.0.1")

How can I read the windows exec code? I already know how to read the command line output from the command, but what if I just want the 0 or 1 telling me whether it was successful or failed?

like image 344
Adam Avatar asked Feb 02 '12 22:02

Adam


People also ask

How do I find my return code using CMD?

To display the exit code for the last command you ran on the command line, use the following command: $ echo $?

How do you exit a script in CMD?

To close an interactive command prompt, the keyboard shortcut ALT + F4 is an alternative to typing EXIT.


1 Answers

Use Process.exitValue() method. You will need to handle the exception thrown if the process has not yet exited and retry.

Or, you could use Process.waitFor() to wait for the process to end and it will return the process exit value also (thanks to increment1).

like image 130
hmjd Avatar answered Oct 06 '22 15:10

hmjd