import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TestJavaCommand {
/**
* 执行命令
*/
public static void executeCommand() {
Runtime runtime = Runtime.getRuntime();
try {
String[] command = {"java", "-version"};
Process process = runtime.exec(command);
// 标准输入流(必须写在 waitFor 之前)
String inStr = consumeInputStream(process.getInputStream());
// 标准错误流(必须写在 waitFor 之前)
String errStr = consumeInputStream(process.getErrorStream()); //若有错误信息则输出
int proc = process.waitFor();
if (proc == 0) {
} else {
System.out.println("执行失败");
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
/**
* @param is
* @return
* @throws IOException
*/
private static String consumeInputStream(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
String s;
StringBuilder sb = new StringBuilder();
while ((s = br.readLine()) != null) {
System.out.println(s);
sb.append(s);
}
return sb.toString();
}
}