/**
* commons-exec.jar
* 根据路径执行文件
* @param path
* @return
* hb
*/
public static String exec(String path){
if(StringUtil.isEmpty(path)){
return null;
}
try {
//创建一个命令行
CommandLine cmdLine = CommandLine.parse(path);
//参数一
cmdLine.addArgument("pararm_1");
//参数二
cmdLine.addArgument("pararm_2");
//执行流
DefaultExecutor executor = new DefaultExecutor();
//定义一组预期退出值
//executor.setExitValue(1);
executor.setExitValues(null);
//监管机构-监管进程执行时间 --单位为毫秒
ExecuteWatchdog watchdog = new ExecuteWatchdog(10);
executor.setWatchdog(watchdog);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream);
executor.setStreamHandler(streamHandler);
int ex = executor.execute(cmdLine);
//拿到执行程序中输出内容
String out = outputStream.toString("gbk");
//拿到执行程序中执行异常内容
String error = errorStream.toString("gbk");
Log.info(CommonsExecUtil.class, "Method[exec]执行命令行文件名称:{},执行输出:{},执行异常信息:{},执行结果:{}", path,out,error,ex);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
exec("D:/svn/1.bat");
}
/****************java直接调用runtime****************************/
public void runbat(String batName) {
try {
Process ps = Runtime.getRuntime().exec(batName);
InputStream in = ps.getInputStream();
int c;
while ((c = in.read()) != -1) {
System.out.print(c);// 如果你不需要看输出,这行可以注销掉
}
in.close();
ps.waitFor();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("child thread done");
}
}