How to get return code in Java after running windows command line command

I am doing something similar in Java right now

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

How can I read the exec Windows code? I already know how to read command line output from a command, but what if I just want 0 or 1 to tell me if it was successful or unsuccessful?

+6
source share
4 answers

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

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

+6
source

next line of code:

 int returnCode = p.waitFor(); 

This is blocked until the process is complete. You can also use the Process.exitValue () method if you do not want to block. See Java6 Class API

+4
source
+2
source

You

 waitFor() 
and then get
 exitValue() 
.
0
source

Source: https://habr.com/ru/post/907523/


All Articles