概要
java执行bat或shell脚本的方式主要有三种方式
1、 使用Runtime.exec
2、 使用ProcessBuilder
3、 使用第三方的工具包commons-exec.jar
使用Runtime.exec
在 Java 中,使用 Runtime.exec() 方法执行外部可执行文件是一个常见的做法。但是,这种方法有一些
限制和潜在的问题,比如它不太容易处理进程的输入/输出流。
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 类名称: ExeRunUtil.
* 类描述: 执行cmd命令
*/
public class ExeRunUtil{
private static Log log = LogFactory.getLog(ExeRunUtil.class);
/**
* 执行cmd命令
* @return 执行结果
*/
public static boolean exec(String[] command) {
Process proc;
try {
proc = Runtime.getRuntime().exec(command);
new StreamReader(proc,proc.getInputStream(),"Output" ).start();
new StreamReader(proc,proc.getErrorStream(),"Error").start();
} catch (IOException ex) {
log.error("IOException while trying to execute " + command,ex);
return false;
}
int exitStatus=1;
try {
exitStatus = proc.waitFor(); //等待操作完成
} catch (java.lang.InterruptedException ex) {
log.error("InterruptedException command: " + exitStatus,ex);
}
if (exitStatus != 0) {
log.error("Error executing command: " + exitStatus);
}
return (exitStatus == 0);
}
}