java中调用cmd命令

在项目中使用到这方面的,备忘一下!
String cmdo = “chmod 777 start.sh”;
String inputtxt = file.getAbsolutePath() + File.separator + “input.txt”;
String outputtxt = file.getAbsolutePath() + File.separator + “output.txt”;
//首先要构建命令
String cmd = “sh start.sh –inputPath=” + inputtxt + ” –outputPath=” + outputtxt;//在Linux系统中
//构建执行文件夹
//这里为传进来的文件
BufferedReader stdInput = null;
BufferedReader stdError = null;
try {
logger.debug(“开始执行cmdo命令:” + cmd + “执行路径:” + file.getAbsolutePath());
Process execo = Runtime.getRuntime().exec(cmdo, null, file);
execo.waitFor();
logger.debug(“开始执行cmd命令:” + cmd + “执行路径:” + file.getAbsolutePath());
Process exec = Runtime.getRuntime().exec(cmd, null, file);
String s = null;
stdInput = new BufferedReader(new InputStreamReader(exec.getInputStream(), StandardCharsets.UTF_8));
stdError = new BufferedReader(new InputStreamReader(exec.getErrorStream(), StandardCharsets.UTF_8));
while ((s = stdInput.readLine()) != null) {
logger.error(s);
}
while ((s = stdError.readLine()) != null) {
logger.error(s);
}
int resulStatus = exec.waitFor();
if (resulStatus != 0) {
throw new Exception(“执行shell脚本出错了”);
}
logger.debug(“执行完shell脚本”);
} catch (InterruptedException e) {
logger.debug(“发生异常了1”);
} catch (Exception e) {
logger.debug(“发生异常了2”);
throw new Exception(“执行shell脚本出错了”);
} finally {
IOUtils.closeQuietly(stdInput);
IOUtils.closeQuietly(stdError);
}

你可能感兴趣的:(代码备忘)