標籤:nes errors rri exec read nal 機制 try throw
最近的新項目有多個地方需要調用shell指令碼,這裡記錄下簡單的shell指令碼調用方法。代碼如下:
private void callSh() {
InputStreamReader stdISR = null;
InputStreamReader errISR = null;
Process process = null;
//調用的指令碼及路徑
String command = "/home/mw/weblogic/test.sh";
try {
process = Runtime.getRuntime().exec(command);
BufferedReader stdBR = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errBR = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = "";
while ((line = stdBR.readLine()) != null) {
System.out.println("STD line:" + line);
}
while ((line = errBR.readLine()) != null) {
System.out.println("ERR line:" +line);
}
} catch (Exception e) {
throw new BusinessException("執行指令碼失敗===="+e);
}finally{
if(stdBR != null){
stdBR.close();
}
if(errBR != null){
errBR.close();
}
if(process != null){
process.destroy();
}
}
}
此代碼只適用一般的shell指令碼調用,如果shell指令碼內容比較多,文法比較複雜,因為沒有很好的容錯機制,使用此方式可能就會出現問題。這裡看過一篇文章,可借鑒:
http://blog.csdn.net/lance_wyvern/article/details/50456903#comments
Java調用shell指令碼