java 执行 bat 或 shell 脚本文件
java 执行 bat 或 shell 脚本的方式主要有三种方式
1、 使用 Runtime.exec
2、 使用 ProcessBuilder
3、 使用第三方的工具包 commons-exec.jar
使用 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(); //等待操作完成