前言
通过Java代码直接启动批处理文件
例如,通过代码启动Tomcat,只需要把tomcat的startup.bat传入到方法里面就可以了!
@Override public void exeCmd(String batPath) { fileUtils.checkPath(batPath); log.info("Start to call cmd process: {}", batPath); StringBuilder sb = new StringBuilder(); try { Process process = Runtime.getRuntime().exec(batPath); InputStream in = process.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line + "\n"); } log.info(sb.toString()); in.close(); process.waitFor(); } catch (Exception e) { log.error("Faild to call cmd process cmd because {}", e.getMessage()); } }
注:本篇文章是直接执行批处理文件,但是有两种情况不能处理:
1.路径里面带有空格的情况,2.环境变量设置问题;
所以博主写了另一篇文章解决了这两个问题:Java——通过Java代码启动批处理文件(二)