最近写代码需要执行linux命令,对这块比较陌生,在摸索了网上资料以及项目里的前辈写的代码后,整理了一下快速上手的过程。

主要使用到两个类Runtime和Process
//获取Runtime实例 Runtime rt = Runtime.getRuntime(); //command是字符串类型,为需要执行的linux命令
Process p = rt.exec(command);// 查看硬盘空间 //初始化缓冲阅读器 BufferedReader in = null;
//获取命令所得的缓冲流结果 in = new BufferedReader(new
InputStreamReader(p.getInputStream()));
//此时就可以对获取的结果in进行操作了,可以使用in.readline()逐步获取每一行的结果内容
 举例一:

现在想要获取磁盘的空间使用情况,用到的命令是:df -h
Runtime rt = Runtime.getRuntime(); Process p = rt.exec("df -h");
BufferedReader in = null; try { in = new BufferedReader(new
InputStreamReader(p.getInputStream())); String str = null; String[] strArray =
null; //逐一对每行内容进行操作 while ((str = in.readLine()) != null) { …… …… } } catch
(Exception e) { logger.info("there has an eror: ", e); } finally { in.close(); }
举例二:

假如需要执行的命令里带有参数、管道等需要分隔成字符串数组进行执行

现在想要获取"/test"目录下的使用磁盘大小,需要使用到的命令:df -h|grep /test
Runtime rt = Runtime.getRuntime(); //分割成数组 String[] commands =
{"/bin/sh","-c","df -hlT|grep \"/test\"}; Process p = rt.exec(commands);
BufferedReader in = null; try { in = new BufferedReader(new
InputStreamReader(p.getInputStream())); String str = null; String[] strArray =
null; while ((str = in.readLine()) != null) { …… …… } } catch (Exception e) {
logger.info("there has an eror: ", e); } finally { in.close(); }
举例三:

假如需要执行的命令有两个,用&&连接,比如要先进入/opt/dmdbms/bin目录下执行dexp命令

需要使用到的命令是cd /opt/dmdbms/bin && ./dexp,直接以字符串形式传入exec()就行。

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信