Java 执行系统命令工具类(commons-exec)

坐标
		<!-- 可以在JVM中可靠地执行外部进程的库。 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-exec</artifactId>
            <version>1.3</version>
        </dependency>

其他版本:https://mvnrepository.com/artifact/org.apache.commons/commons-exec

工具类
package com.example.demo.exec;

import org.apache.commons.exec.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 执行系统命令工具类
 *
 * @author https://blog.csdn.net/chen_2890
 */
public class CommandUtil {

    private static Logger logger = LoggerFactory.getLogger(CommandUtil.class.getSimpleName());
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final Long TIMEOUT = 10000L;

    /**
     * 执行指定命令
     *
     * @param command 命令
     * @return 命令执行完成返回结果
     * @throws RuntimeException 失败时抛出异常,由调用者捕获处理
     */
    public synchronized static String exeCommand(String command) throws RuntimeException {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            int exitCode = exeCommand(command, out);
            if (exitCode == 0) {
                logger.info("命令运行成功:" + System.currentTimeMillis());
            } else {
                logger.info("命令运行失败:" + System.currentTimeMillis());
            }
            return out.toString(DEFAULT_CHARSET);
        } catch (Exception e) {
            logger.info(ExceptionUtils.getStackTrace(e));
            throw new RuntimeException(ExceptionUtils.getStackTrace(e));
        }
    }

    /**
     * 执行指定命令,输出结果到指定输出流中
     *
     * @param command 命令
     * @param out     执行结果输出流
     * @return 执行结果状态码:执行成功返回0
     * @throws ExecuteException 失败时抛出异常,由调用者捕获处理
     * @throws IOException      失败时抛出异常,由调用者捕获处理
     */
    public synchronized static int exeCommand(String command, OutputStream out) throws ExecuteException, IOException {
        CommandLine commandLine = CommandLine.parse(command);
        PumpStreamHandler pumpStreamHandler = null;
        if (null == out) {
            pumpStreamHandler = new PumpStreamHandler();
        } else {
            pumpStreamHandler = new PumpStreamHandler(out);
        }
        // 设置超时时间为10秒
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(pumpStreamHandler);
        executor.setWatchdog(watchdog);
        return executor.execute(commandLine);
    }

    public static void main(String[] args) {
        logger.info(exeCommand("pwd"));
        logger.info(exeCommand("ls"));
    }

}
原来微信打赏还可以备注哦

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值