java调用shell命令并获取执行结果的示例
作者:arkblue 时间:2021-07-06 06:17:54
使用到Process和Runtime两个类,返回值通过Process类的getInputStream()方法获取
package ark;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class ReadCmdLine {
public static void main(String args[]) {
Process process = null;
List<String> processList = new ArrayList<String>();
try {
process = Runtime.getRuntime().exec("ps -aux");
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
processList.add(line);
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
for (String line : processList) {
System.out.println(line);
}
}
}
调用shell脚本,判断是否正常执行,如果正常结束,Process的waitFor()方法返回0
public static void callShell(String shellString) {
try {
Process process = Runtime.getRuntime().exec(shellString);
int exitValue = process.waitFor();
if (0 != exitValue) {
log.error("call shell failed. error code is :" + exitValue);
}
} catch (Throwable e) {
log.error("call shell failed. " + e);
}
}
来源:https://blog.csdn.net/arkblue/article/details/7897396
标签:java,shell
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Javaweb基础入门requse原理与使用
2021-10-07 20:55:29
![](https://img.aspxhome.com/file/2023/6/77096_0s.png)
Java线程池ThreadPoolExecutor源码深入分析
2023-11-09 19:49:36
浅谈SpringCloud实现简单的微服务架构
2023-05-22 12:59:34
![](https://img.aspxhome.com/file/2023/0/75490_0s.png)
浅谈java中String StringBuffer StringBuilder的区别
2023-11-29 13:34:40
springboot配置redis过程详解
2022-10-13 12:41:30
![](https://img.aspxhome.com/file/2023/7/69887_0s.png)
Java如何在 Word 中设置上、下标
2023-10-15 21:04:10
![](https://img.aspxhome.com/file/2023/2/77972_0s.png)
springBoot+dubbo+zookeeper实现分布式开发应用的项目实践
2021-11-22 02:03:25
![](https://img.aspxhome.com/file/2023/8/85518_0s.png)
C#微信公众号开发之自定义菜单
2023-01-23 02:07:08
![](https://img.aspxhome.com/file/2023/9/68079_0s.png)
java的线程池框架及线程池的原理
2023-11-16 22:04:51
java判断list不为空的实现,和限制条数不要在一起写
2022-01-24 13:14:38
Java实现输出数字三角形实例代码
2023-08-25 02:09:51
![](https://img.aspxhome.com/file/2023/4/58304_0s.png)
java 实现线程同步的方式有哪些
2023-01-13 01:26:14
使用java编程从0到1实现一个简单计算器
2023-12-06 04:47:53
![](https://img.aspxhome.com/file/2023/1/83011_0s.png)
【Redis缓存机制】详解Java连接Redis_Jedis_事务
2023-05-23 19:59:55
![](https://img.aspxhome.com/file/2023/7/72917_0s.jpg)
Java 多线程传值的四种方法
2022-02-03 08:16:44
![](https://img.aspxhome.com/file/2023/4/79944_0s.png)
java原生序列化和Kryo序列化性能实例对比分析
2023-11-26 16:04:20
C#使用DropDownList绑定添加新数据的方法汇总
2023-05-08 03:20:56
Java中重载与重写的对比与区别
2021-08-29 13:22:31
Springboot使用test无法启动问题的解决
2021-07-03 22:09:23
![](https://img.aspxhome.com/file/2023/2/83432_0s.png)
鉴权认证+aop+注解+过滤feign请求的实例
2022-06-05 14:25:34
![](https://img.aspxhome.com/file/2023/2/74882_0s.jpg)