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

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 }
点赞
收藏

评论区

加载中...

相关推荐

Python—执行系统命令的四种方法(os.system、os.popen、commands、subprocess)

一、os.system方法这个方法是直接调用标准C的system()函数,仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息。os.system(cmd)的返回值。如果执行成功,那么会返回0,表示命令执行成功。否则,则是执行错误。使用os.system返回值是脚本的退出状态码,该方法在调用完shell脚本后

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Linux Shell DAY6

shell脚本介绍shell脚本结构和执行date命令用法shell脚本中的变量脚本中的逻辑判断shell脚本介绍shell是什么shell是一种脚本语言可以使用逻辑判断、循环等语法可以自定义函数

0615 shell编程1

0615shell编程1一、shell脚本介绍shell是一种脚本语言和传统的开发语言比较,会比较简单shell有自己的语法;可以使用逻辑判断、循环等语法可以自定义函数,目的就是为了减少重复的代码shell是系统命令的集合