操作系统命令工具Util

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 + "
";
                    // 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);
                }
            }
        }
    }

}
原文地址:https://www.cnblogs.com/eaglediao/p/6636406.html