赞
踩
- //获取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()就行。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。