Skip to content

Instantly share code, notes, and snippets.

@smallsong
Created September 30, 2018 06:21
Show Gist options
  • Save smallsong/6db66a8684ecd89d32c4267db2966108 to your computer and use it in GitHub Desktop.
Save smallsong/6db66a8684ecd89d32c4267db2966108 to your computer and use it in GitHub Desktop.
java 执行shell file
public class ExecuteSHFile {
private static Logger logger = LoggerFactory.getLogger(ExecuteSHFile.class);
public static String executeSHFile(String shutdown_path) throws Exception {
//执行XXX.sh脚本
Process ps = Runtime.getRuntime().exec("sh "+shutdown_path);
//阻塞,直到上述命令执行完成,当返回值为0时表示执行成功
int resultCode = ps.waitFor();
String result=null;
logger.info("resultCode"+resultCode);
if(resultCode == 0){
//只能接收脚本echo打印的数据,并且是echo打印的最后一次数据
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = br.readLine();
while(line != null){
logger.info(line);
line = br.readLine();
sb.append(line).append("\n");
}
result = sb.toString();
} else {
logger.info("resultCode 不是0,线程没有正常结束 ========== " + resultCode);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment