六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 53|回复: 0

调用系统的DOS命令方法执行需要的命令

[复制链接]

升级  76%

8

主题

8

主题

8

主题

童生

Rank: 1

积分
38
 楼主| 发表于 2013-1-26 14:10:21 | 显示全部楼层 |阅读模式
package com.huaweisymantec.core.utils;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.Reader;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 命令行命令执行工具类 *  * @author s00108907 *  */public final class CommandUtils {    private static final Logger LOG = LoggerFactory.getLogger(CommandUtils.class);    /**     * 调用系统的DOS命令方法执行需要的命令     *      * @param command 要执行的命令     * @return 执行结果     * @throws IOException     */    public static String exec(String command) throws IOException {        return exec(null, command);    }    /**     * 调用系统的DOS命令方法执行需要的命令     *      * @param directory 此进程的工作目录     * @param command 要执行的命令     * @return 执行结果     * @throws IOException     */    public static String exec(String directory, String command) throws IOException {        InputStream in = null;        Reader reader = null;        BufferedReader br = null;        try {            ProcessBuilder pb;            if (System.getProperty("os.name").indexOf("Windows") == -1) {                pb = new ProcessBuilder("/bin/sh", "-c", command);            } else {                pb = new ProcessBuilder("cmd", "/c", command);            }            if (StringUtils.isNotBlank(directory)) {                pb.directory(new File(directory));            }            // merge the error output with the standard output            pb.redirectErrorStream(true);            LOG.debug("Now exceuting:{}", command);            Process p = pb.start();            in = p.getInputStream();            reader = new InputStreamReader(in, "gb2312");            br = new BufferedReader(reader);            StringBuffer lines = new StringBuffer();            String line = null;            while ((line = br.readLine()) != null) {                lines.append(line).append("\r\n");            }            LOG.debug("Exceuting result:{}", lines.toString());            return lines.toString();        } finally {            if (reader != null) {                reader.close();            }            if (br != null) {                br.close();            }            if (in != null) {                in.close();            }        }    }}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表