失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > java runtime 返回值_Java Runtime.exec()注意事项 | 学步园

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

时间:2023-05-22 13:04:23

相关推荐

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

转载自:/flying881114/archive//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"});

参考资料:

/westwin/archive//04/22/358377.aspx

/moreorless/archive//05/15/4182883.aspx

/HEYUTAO007/archive//06/30/5705499.aspx

如果觉得《java runtime 返回值_Java Runtime.exec()注意事项 | 学步园》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。