How to capture the exit status of shell commands in Java?

I am creating a JUnit test file for my csvreader I am reading the contents of the CSV file and writing the contents to another file I want to use the diff utility to compare them. I want to use the exit state of diff to know whether the contents are the same Usually $? Gives the exit status, but I don't know how to capture it and use it in my code Who can help me in this regard?

That's 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 under the condition of if

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

Even other suggestions are popular:)

Solution

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();

Don't forget that you should read the contents of InputStream. Even if you don't care, some processes will block (not complete) before reading the output buffer

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>