Java执行shell脚本并返回结果两种方法的完整代码

您所在的位置:网站首页 java实现读取sql脚本文件并执行命令 Java执行shell脚本并返回结果两种方法的完整代码

Java执行shell脚本并返回结果两种方法的完整代码

2024-07-06 03:04| 来源: 网络整理| 查看: 265

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 runShell(String shStr) { List strList = new ArrayList(); 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; }

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3