Java中调用外部命令
public class ExecCommond{
public ExecCommond(){}
/**
* 执行一条命令
* @param execStr String 命令字符串
* @return String 执行命令错误时的信息。
*/
public static String exec(String execStr) {
Runtime runtime = Runtime.getRuntime(); 取得当前运行期对象
String outInfo=""; //执行错误的输出信息
try {
String[] args = new String[] {"sh", "-c", execStr};//执行linux下的命令
//执行windows下的命令
// String[] args = new String[] {"cmd", "-c", execStr};
Process proc = runtime.exec(args); //启动另一个进程来执行命令
InputStream in = proc.getErrorStream();//得到错误信息输出。
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
while ( (line = br.readLine())
!= null) {
outInfo = outInfo + line + "\n";
System.out.println(outInfo);
}
// 检查命令是否失败。
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " +
proc.exitValue());
}
}
catch (InterruptedException e) {
System.err.print(e);
e.printStackTrace();
}
评书:
ps:
1 import java.io.BufferedReader;
2 import java.io.IOException;
3 import java.io.InputStream;
4 import java.io.InputStreamReader;
5 import java.io.OutputStream;
6
7 /**
8 *
9 * @author liyang
10 */
11
12 public class ConsoleStream {
13
14 public static void main(String[] args) throws IOException, InterruptedException {
15 String info;
16 System.out.println("Here we go ");
17 String[] cmd = new String[] {"cmd","/c","javac d://helloworld.java"};
18 Process p = Runtime.getRuntime().exec(cmd);
19
20 // OutputStream os = p.getOutputStream();
21 InputStream stdin = p.getInputStream(); //
22 InputStream stderr = p.getErrorStream();
23
24 InputStreamReader isr = new InputStreamReader(stdin);
25 InputStreamReader esr = new InputStreamReader(stderr);
26
27 BufferedReader readerIn = new BufferedReader(isr);
28 BufferedReader readerErr= new BufferedReader(esr);
29
30 System.out.println("in:");
31 while ((info = readerIn.readLine()) != null) {
32 System.out.println(info);
33 }
34
35 System.out.println("error");
36 while ((info = readerErr.readLine()) != null) {
37 System.out.println(info);
38 }
39 int retcode;
40 retcode = p.waitFor();
41
42 System.out.println("process end code: " + retcode);
43 p.destroy();
44 }
45 }