java 捕捉程序退出,如何在Java中捕获shell命令的退出状态?

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

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值