Java执行shell脚本并返回结果两种方法的完整代码
简单的是直接传入String字符串,这种不能执行echo 或者需要调用其他进程的命令(比如调用postfix发送邮件命令就不起作用)
执行复杂的shell建议使用String[]方式传递(对外可以封装后也传入String字符串)。
1/** 2 * 运行shell脚本 3 * @param shell 需要运行的shell脚本 4 */ 5 public static void execShell(String shell){ 6 try { 7 Runtime.getRuntime().exec(shell); 8 } catch (Exception e) { 9 e.printStackTrace(); 10 } 11 } 12 13 /** 14 * 运行shell脚本 new String[]方式 15 * @param shell 需要运行的shell脚本 16 */ 17 public static void execShellBin(String shell){ 18 try { 19 Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shell},null,null); 20 } catch (Exception e) { 21 e.printStackTrace(); 22 } 23 } 24 25 26 /** 27 * 运行shell并获得结果,注意:如果sh中含有awk,一定要按new String[]{"/bin/sh","-c",shStr}写,才可以获得流 28 * 29 * @param shStr 30 * 需要执行的shell 31 * @return 32 */ 33 public static List<String> runShell(String shStr) { 34 List<String> strList = new ArrayList<String>(); 35 try { 36 Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null); 37 InputStreamReader ir = new InputStreamReader(process.getInputStream()); 38 LineNumberReader input = new LineNumberReader(ir); 39 String line; 40 process.waitFor(); 41 while ((line = input.readLine()) != null){ 42 strList.add(line); 43 } 44 } catch (Exception e) { 45 e.printStackTrace(); 46 } 47 return strList; 48 }