How to capture the exit status of a shell command in Java?

人盡茶涼 提交于 2020-01-13 08:39:11

问题


I'm creating a Junit test file for my CSVreader. I'm reading the contents of CSV files and writing the contents into another file. I want to compare them using diff utility and I want to use the exit status of diff to know whether the contents are same or not. Generally $? gives the 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 how my code looks

 boolean hasSameContents = false;

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

After this I want to get the exit status and use it in a if condition like this

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

Even alternative suggestions appreciated. :)


回答1:


You're 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();

Don't forget, you should read the contents of the InputStream even if you don't care, some processes will choke (not finish) until the output buffer has been read...




回答2:


You can try using ProcessBuilder class to create a Processobject, whose exitValue() should help you.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/12892665/how-to-capture-the-exit-status-of-a-shell-command-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!