java执行cmd命令工具实现

在某些情况下,java也会调用cmd执行某些命令。例如重启啊什么的,之前写了一个执行cmd命令的一个工具类,大家可以参考一下,根据自身情况进行调整。

执行String字符串类的命令

public String runCommands(String cmds){  
  
        String str = "";  
        String errStr = "";  
        String charset = Charset.defaultCharset().toString();  
        try {  
            Process p = Runtime.getRuntime().exec(cmds);  
            InputStream err = p.getErrorStream();  
            InputStream in = p.getInputStream();  
            str = processStdout(in, charset);  
            errStr = processStdout(err, charset);  
            if(!StringUtils.isEmpty(errStr)){  
                return str+errStr;  
            }  
        } catch (IOException e) {  
            errStr = e.getMessage();  
            return errStr;  
        }  
        return str;  
  
    }  
执行String[]类的命令
public String runCommands(String[] cmd){  
  
        String str = "";  
        String errStr = "";  
        String charset = Charset.defaultCharset().toString();  
        try {  
            Process p = Runtime.getRuntime().exec(cmd);  
            InputStream err = p.getErrorStream();  
            InputStream in = p.getInputStream();  
            str = processStdout(in, charset);  
            errStr = processStdout(err, charset);  
            if(!StringUtils.isEmpty(errStr)){  
                return str+errStr;  
            }  
        } catch (IOException e) {  
            errStr = e.getMessage();  
            return errStr;  
        }  
        return str;  
  
    }  
解析返回信息
public String processStdout(InputStream in, String charset) throws IOException {  
        String s = "";  
        String str = "";  
        InputStreamReader insr = new InputStreamReader(in);  
        BufferedReader buffer = new BufferedReader(insr);  
        try {  
            while ((s=buffer.readLine())!= null){  
                if(StringUtil.isEmpty(str)){  
                    str = str+s;  
                }else{  
                    str = "\n"+str+s;  
                }  
            }  
        } catch (IOException e) {  
            throw e;  
        } finally {  
            buffer.close();  
            insr.close();  
        }  
  
        return str;  
    }  


你可能感兴趣的:(java执行cmd命令工具实现)