Java執行shell腳本並返回結果兩種方法的完整代碼
簡單的是直接傳入String字符串,這種不能執行echo 或者需要調用其他進程的命令(比如調用postfix發送郵件命令就不起作用)
執行復雜的shell建議使用String[]方式傳遞(對外可以封裝后也傳入String字符串)。
/** * 運行shell腳本 * @param shell 需要運行的shell腳本 */ public static void execShell(String shell){ try { Runtime.getRuntime().exec(shell); } catch (Exception e) { e.printStackTrace(); } } /** * 運行shell腳本 new String[]方式 * @param shell 需要運行的shell腳本 */ public static void execShellBin(String shell){ try { Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shell},null,null); } catch (Exception e) { e.printStackTrace(); } } /** * 運行shell並獲得結果,注意:如果sh中含有awk,一定要按new String[]{"/bin/sh","-c",shStr}寫,才可以獲得流 * * @param shStr * 需要執行的shell * @return */ public static List<String> runShell(String shStr) { List<String> strList = new ArrayList<String>(); try { Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null); InputStreamReader ir = new InputStreamReader(process.getInputStream()); LineNumberReader input = new LineNumberReader(ir); String line; process.waitFor(); while ((line = input.readLine()) != null){ strList.add(line); } } catch (Exception e) { e.printStackTrace(); } return strList; }