如何在Java中捕获shell命令的退出状态? [英] How to capture the exit status of a shell command in Java?

查看:463
本文介绍了如何在Java中捕获shell命令的退出状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的CSVreader创建一个Junit测试文件。我正在读取CSV文件的内容并将内容写入另一个文件。我想使用diff实用程序比较它们,我想使用diff的退出状态来知道内容是否相同。一般是$?给出退出状态,但我不知道如何捕获它并在我的代码中使用它。在这方面有谁可以帮助我?

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

在此之后我想获得退出状态并在if这样的条件下使用它

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. :)

推荐答案

您正在寻找 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();

不要忘了,你应该阅读 InputStream的内容即使你不在乎,有些进程会在读取输出缓冲区之前阻塞(不完成)...

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...

这篇关于如何在Java中捕获shell命令的退出状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆