1. 如果只是执行而不需要得到返回结果
String shell="command line";
String command="command line";
try {
Runtime rt=Runtime.getRuntime();
rt.exec(command);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
2. 如果需要得到返回结果,可以用Process
Process process;
StringBuilder sb=new StringBuilder();
try {
Runtime rt=Runtime.getRuntime();
//String shell="command line";
String[] shell={"command line",args[0]}; //命令可以用数组的方式,这样可以处理参数中的特殊字符,如空格。
process=rt.exec(shell);
InputStreamReader reader=new InputStreamReader(process.getInputStream());
BufferedReader br=new BufferedReader(reader);
String line;
while((line=br.readLine())!=null){
sb.append(line);
}
System.out.println(sb);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}