import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; /**
* 操作系统命令工具
*/
public class ExecUtil {
private static final Logger logger = LogManager.getLogger(ExecUtil.class); /**
* 执行一条操作系统命令*/
public static CmdInfo exec(String command) {
logger.info("exec cmd begin: " + command);
try{
Process ps = Runtime.getRuntime().exec(command);
ps.waitFor();
StreamGobbler errorGobbler = new StreamGobbler(ps.getErrorStream());
errorGobbler.start();
StreamGobbler outGobbler = new StreamGobbler(ps.getInputStream());
outGobbler.start();
outGobbler.join();
CmdInfo info = new CmdInfo(ps.exitValue(), errorGobbler.getInfo(), outGobbler.getInfo());
return info;
}
catch(Exception e){
logger.info("exec cmd error: ", e);
throw new RuntimeException(e);
}
finally{
Runtime.getRuntime().runFinalization();
}
} public static CmdInfo exec(String[] command) { try{
Process ps = Runtime.getRuntime().exec(command);
ps.waitFor();
StreamGobbler errorGobbler = new StreamGobbler(ps.getErrorStream());
errorGobbler.start();
StreamGobbler outGobbler = new StreamGobbler(ps.getInputStream());
outGobbler.start();
outGobbler.join();
CmdInfo info = new CmdInfo(ps.exitValue(), errorGobbler.getInfo(), outGobbler.getInfo());
return info;
}
catch(Exception e){
logger.info("exec cmd error: ", e);
throw new RuntimeException(e);
}
finally{
Runtime.getRuntime().runFinalization();
// Runtime.getRuntime ().gc();
}
} public static boolean execCmdAndWait(String cmd, long timeout, TimeUnit unit) {
try {
Process process = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", cmd});
process.waitFor(timeout, unit);
} catch (InterruptedException | IOException e) {
logger.error("exec cmd: " + cmd + " and wait " + timeout + " " + unit + " go wrong", e);
return false;
}
return true;
}/**
* 命令信息
*/
public static class CmdInfo implements Serializable { private static final long serialVersionUID = 7416244152344549775L;
private int exitValue;
private String errorInfo;
private String msgInfo; public CmdInfo(int exitValue, String errorStreamInfo, String inputStreamInfo) {
this.exitValue = exitValue;
this.errorInfo = errorStreamInfo;
this.msgInfo = inputStreamInfo;
} public String getErrorInfo() { return errorInfo;
}
public void setErrorInfo(String errorStreamInfo) { this.errorInfo = errorStreamInfo;
} public int getExitValue() { return exitValue;
} public void setExitValue(int exitValue) { this.exitValue = exitValue;
} public String getMsgInfo() { return msgInfo;
} public void setMsgInfo(String inputStreamInfo) { this.msgInfo = inputStreamInfo;
} } /**
* 处理Process的stdout和stderr的类
*/
static class StreamGobbler extends Thread { private InputStream is; private OutputStream os; private String info = ""; public StreamGobbler(InputStream is) { this(is, null);
} public StreamGobbler(InputStream is, OutputStream redirect) { this.is = is;
this.os = redirect;
} public String getInfo() { return this.info;
} /*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run() { PrintWriter pw = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
pw = null;
if(os != null){
pw = new PrintWriter(os);
} isr = new InputStreamReader(is);//,"GBK"
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null){
if(pw != null){
pw.println(line);
}
info += line + "\n";
// System.out.println (line);
}
if(pw != null){
pw.flush();
}
}
catch(IOException ioe){
throw new RuntimeException(ioe);
}
finally{
try{
if(pw != null){
pw.close();
}
if(isr != null){
isr.close();
}
if(br != null){
br.close();
}
}
catch(IOException e){
throw new RuntimeException(e);
}
}
}
} }

操作系统命令工具Util的更多相关文章

  1. 自己封装的poi操作Excel工具类

    自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...

  2. 自己的包poi操作Excel工具

    在前面的文章<使用poi读写Excel>中分享了一下poi操作Excel的简单演示样例.这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完毕的功能是:读取Excel.汇总E ...

  3. java日期操作常用工具

    java日期操作常用工具 package com..util; import java.sql.Timestamp; import java.text.SimpleDateFormat; import ...

  4. Java操作Redis工具类

    依赖 jar 包 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis< ...

  5. Redis操作Set工具类封装,Java Redis Set命令封装

    Redis操作Set工具类封装,Java Redis Set命令封装 >>>>>>>>>>>>>>>>& ...

  6. Redis操作List工具类封装,Java Redis List命令封装

    Redis操作List工具类封装,Java Redis List命令封装 >>>>>>>>>>>>>>>> ...

  7. Redis操作Hash工具类封装,Redis工具类封装

    Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...

  8. Redis操作字符串工具类封装,Redis工具类封装

    Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...

  9. java中文件操作的工具类

    代码: package com.lky.pojo; import java.io.BufferedReader; import java.io.BufferedWriter; import java. ...

随机推荐

  1. 在Logstash的配置文件中对日志事件进行区分

    1.多个日志文件作为输入源 input { # 通过给日志事件定义类型来区分 file { path => ["/var/log/nginx/access.log"] typ ...

  2. Docker学习の更改Docker的目录

    一.更改虚拟磁盘的目录 虚拟机的默认存储位置是C:\Users\Administrator\.docker\machine\machines ,后期docke镜像文件会不断增加,为了给系统盘减负,最好 ...

  3. iOS开发系列-修改项目工程名

    当前有项目工程名为iOS,需要修改工程名为IFLY.在修改前注意备份项目 修改项目名 出现弹框,点击Rename 修改工程目录文件名 注意Tests与UITests不要删除 选中IFLY.xcodep ...

  4. jpa 踩坑 SQLGrammarException

    SQLGrammarException could not execute query  cause by not found column id ,, id指的是,返回的结果没有Id 封装结果集出错 ...

  5. Python 读取本地*.txt文件 替换 内容 并保存

    # r    以只读的方式打开文件,文件的描述符放在文件的开头# w    打开一个文件只用于写入,如果该文件已经存在会覆盖,如果不存在则创建新文件 #路径path = r"D:\pytho ...

  6. php+jquery 上拉加载

    <script type="text/javascript"> var resflow = true,pages =2; var ps=$("#ids&quo ...

  7. datetime模块练习

    #_author:来童星#date:2019/12/6#1.获取当前日期import datetimeprint(datetime.date.today())# 2019-12-06#2.使用toda ...

  8. 5.1_Spring Boot2.x安装Docker

    1.简介 Docker是一个开源的应用容器引擎:是一个轻量级容器技术: Docker 是一个开源的应用容器引擎,基于Go 语言并遵从Apache2.0协议开源.Docker 可以让开发者打包他们的应用 ...

  9. Django杂篇(2)

    目录 Django杂篇(2) cookie与session cookie session django中间件 自定义中间件 跨站请求伪造(csrf) CSRF的解决方案 Django杂篇(2) 本文主 ...

  10. 1.1python基础_基础

    1_编码 默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串. 当然你也可以为源码文件指定不同的编码: # -*- coding: UTF-8 -*- ...