Java执行shell脚本并返回结果两种方法的完整代码
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; }
大自然,飘然的风,QQ群: python技术交流群:453879716,人工智能深度学习群:251088643
golang技术交流群:316397059,vuejs技术交流群:458915921 囤币一族:621258209,有兴趣的可以加入
微信公众号: 心禅道(xinchandao)投资论道
golang技术交流群:316397059,vuejs技术交流群:458915921 囤币一族:621258209,有兴趣的可以加入
微信公众号: 心禅道(xinchandao)投资论道
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 协程本质是函数加状态机——零基础深入浅出 C++20 协程
· 编码之道,道心破碎。
· 记一次 .NET 某发证机系统 崩溃分析
· 微服务架构学习与思考:SOA架构与微服务架构对比分析
· tomcat为什么假死了
· 知名开源项目Alist被收购!惹程序员众怒,开团炮轰甲方
· 突发,小红书开发者后门被破解?!
· 历时半年,我将一个大型asp.net的零代码快速开发平台转成了java
· [原创]《C#高级GDI+实战:从零开发一个流程图》第03章:画一个线,连接两个矩形!
· C# 将 CSV 转化为 Excel