现在的位置: 首页 > 综合 > 正文

Java Runtime.exec()注意事项

2019年03月25日 ⁄ 综合 ⁄ 共 1108字 ⁄ 字号 评论关闭

转载自: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

抱歉!评论已关闭.