How to capture shell command exit status in Java?

I am creating a Junit test file for my CSVreader. I am reading the contents of CSV files and writing the contents to another file. I want to compare them using the diff utility, and I want to use the diff output status to find out if they match or not. Usually $? gives exit status, but I don’t know how to capture it and use it in my code. Can anyone help me in this regard?

This is what my code looks like

boolean hasSameContents = false; command="diff "+mp.get("directory")+"/"+fileName+" "+mp.get("outdir")+"/"+fileName; p= Runtime.getRuntime().exec(command); p.waitFor(); 

After that, I want to get the exit status and use it in the following conditions:

  if(exit_status==0) hasSameContents = true; else hasSameContents = false; 

Even alternative suggestions appreciated. :)

+4
source share
4 answers

Are you looking for Process # exitValue

 String command = "diff "+mp.get("directory")+"/"+fileName+" "+mp.get("outdir")+"/"+fileName; Process p = Runtime.getRuntime().exec(command); p.waitFor(); int exitStatus = p.exitValue(); 

Do not forget that you should read the contents of the InputStream , even if you do not care, some processes will throttle (not terminate) until the output buffer is read ...

+11
source

You can try using the ProcessBuilder class to create a Process object that exitValue() should help you.

+3
source

Use the waitFor () method of the Process class . It returns the int value, the return value of the process.

+2
source

Runtime.exec() and friends return a Process object that has an exitValue() method that returns an exit code.

+1
source

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


All Articles