java执行Linux命令的方法
本文实例讲述了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程序设计有所帮助。
相关文章
一文掌握Spring 中 @Component 和 @Bean 区别(最新推荐)
@Component 用于标识一个普通的类,@Bean用于配置类里面,在方法上面声明和配置 Bean 对象,这篇文章主要介绍了Spring 中 @Component 和 @Bean 区别(最新推荐),需要的朋友可以参考下2024-04-04
PowerJob AbstractSqlProcessor方法工作流程源码解读
这篇文章主要为大家介绍了PowerJob AbstractSqlProcessor方法工作流程源码解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2024-01-01
Springboot @Value注入boolean设置默认值方式
这篇文章主要介绍了Springboot @Value注入boolean设置默认值方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-03-03


最新评论