您的位置:首页 > 运维架构 > Linux

java执行linux命令注意事项

2014-05-08 13:16 573 查看
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/flying881114/archive/2011/03/23/6272472.aspx

 

参考资料:
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: