java runtime 返回值_Java Runtime.exec()注意事项 | 学步园

转载自:http://blog.csdn.net/flying881114/archive/2011/03/23/6272472.aspx

0. Runtime.exec()用来执行外部程序或命令

1. Runtime.exec() 有四种调用方法

* public Process exec(String command);

* public Process exec(String [] cmdArray);

* public Process exec(String command, String [] envp);

* public Process exec(String [] cmdArray, String [] envp);

2. 得到程序执行返回值, 0为success

需要用waitFor()函数,比如

Process p = Runtime.getRuntime().exec("javac");

(处理.....)

int exitVal = p.waitFor();

3. 得到程序执行的结果或错误信息

需要用BufferedInputStream 和 BufferReader来得到,否则程序会hang

比如得到错误信息用p.getErrorStream(),然后输出即可:

BufferedInputStream in = new BufferedInputStream(p.getErrorStream());

BufferedReader br = new BufferedReader(new InputStreamReader(in));

4. Runtime.exec() 不等同于直接执行command line命令!

啊,我算是在这里吃了苦头了。Runtime.exec()很有局限性,对有些命令不能直接把command line里的内容当作String参数传给exec().

比如重定向等命令。举个例子:

javap -l xxx > output.txt

这时要用到exec的第二种重载,即input 参数为String[]:

Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","javap -l xxx > output.txt"});

参考资料:

http://blog.csdn.net/westwin/archive/2005/04/22/358377.aspx

http://blog.csdn.net/moreorless/archive/2009/05/15/4182883.aspx

http://blog.csdn.net/HEYUTAO007/archive/2010/06/30/5705499.aspx

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值