java中呼叫本地指令碼
阿新 • • 發佈:2018-11-01
java中可以呼叫本地指令碼,也可以遠端呼叫shell指令碼,但是java呼叫遠端指令碼不安全,一般不這麼做,那該怎麼呼叫呢?
建議在本地寫個指令碼呼叫遠端指令碼,在java程式中呼叫本地指令碼,具體程式碼:
private int execShell(String shellPath, String... params) {
StringBuilder command = new StringBuilder(shellPath).append(" ");
for (String param : params) {
command.append(param).append(" " );
}
BufferedReader br = null;
StringBuilder sb = null;
try {
Process process = Runtime.getRuntime().exec(command.toString());
process.waitFor();
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
LOG.error("execShell() error, shellPath: {}, params: {}", shellPath, params, e);
return -2;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "".equals(sb.toString()) ? 0 : Integer.parseInt(sb.toString());
}
注意:如果指令碼執行成功,process.waitFor()會返回0狀態碼;如果指令碼執行出錯,本根據不同的錯誤返回不同的狀態碼,此時需要使用流獲取到指令碼返回的狀態