java执行Linux命令的方法
作者:shichen2014 时间:2023-01-23 21:36:10
本文实例讲述了java执行Linux命令的方法。分享给大家供大家参考。具体实现方法如下:
public class StreamGobbler extends Thread {
InputStream is;
String type;
public StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (type.equals("Error")) {
System.out.println("Error :" + line);
} else {
System.out.println("Debug:" + line);
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
private void shell(String cmd)
{
String[] cmds = { "/bin/sh", "-c", cmd };
Process process;
try
{
process = Runtime.getRuntime().exec(cmds);
StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "Error");
StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "Output");
errorGobbler.start();
outputGobbler.start();
try
{
process.waitFor();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
其中参数 cmd 为Linux命令。每次只能执行一条命令。
1.Java Runtime.exec()注意事项:
① 永远要在调用waitFor()方法之前读取数据流
② 永远要先从标准错误流中读取,然后再读取标准输出流
2.最好的执行系统命令的方法就是写个bat文件或是shell脚本。
希望本文所述对大家的Java程序设计有所帮助。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android开发之ListView的head消失页面导航栏的渐变出现和隐藏
C#操作注册表的方法
Spring Boot + thymeleaf 实现文件上传下载功能
![](https://img.aspxhome.com/file/2023/0/61680_0s.png)
java生成随机数的方法
![](https://img.aspxhome.com/file/2023/4/65354_0s.jpg)
44条Java代码优化建议
![](https://img.aspxhome.com/file/2023/6/62776_0s.png)
C++类常量和类枚举
![](https://img.aspxhome.com/file/2023/6/109786_0s.jpg)
Spring Boot中lombok的安装与使用详解
![](https://img.aspxhome.com/file/2023/5/66055_0s.jpg)
C# ManualResetEvent用法详解
![](https://img.aspxhome.com/file/2023/1/113811_0s.png)
java使用回溯法求解数独示例
Java使用Socket通信传输文件的方法示例
C#制作鹰眼的详细全过程(带注释)实例代码
C# FileStream实现大文件复制
![](https://img.aspxhome.com/file/2023/8/96348_0s.png)
spring Bean的初始化过程解析
![](https://img.aspxhome.com/file/2023/2/103972_0s.png)
Java Socket使用加密协议进行传输对象的方法
Unity3D动态对象优化代码分享
Java框架设计灵魂之反射的示例详解
Spring Cloud Alibaba Nacos Config进阶使用
![](https://img.aspxhome.com/file/2023/7/125627_0s.png)
C#中的值传递和引用传递详细解析
android实现点击按钮控制图片切换
![](https://img.aspxhome.com/file/2023/0/126770_0s.gif)
C#之CLR内存字符串常量池(string)
![](https://img.aspxhome.com/file/2023/1/106531_0s.png)