java 运行 shell/cmd 命令

原创文章,欢迎转载:http://miao.blog/article/java-execute-shell-command

package com.marssvn.svnapi.common;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import java.io.IOException;

public class CommandUtils {

    /**
     * log4j.Logger
     */
    private static Logger logger = Logger.getLogger("CommandUtils");

    /**
     * execute command, windows: cmd,  linux: /bin/sh
     *
     * @param command command
     * @return Process
     * @throws IOException IOException
     */
    public static Process execute(String command) throws IOException {
        // os
        String os = System.getProperty("os.name").toLowerCase();

        Process process;
        if (os.startsWith("win")) {
            logger.debug("cmd: " + command);
            process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", command});
        } else {
            logger.debug("/bin/sh: " + command);
            process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command});
        }
        String errorMsg = IOUtils.toString(process.getErrorStream(), System.getProperty("sun.jnu.encoding"));
        if (StringUtils.isNotBlank(errorMsg)) {
            logger.error(errorMsg);
        }
        return process;
    }
}
// 调用代码
CommandUtils.execute("echo ipconfig > ip.txt");
评论
喵喵咪

喵喵咪

2018-12-17

哈哈给力

喵喵咪

喵喵咪

2019-03-05

喵喵咪