栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 调用命令行

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 调用命令行

主要针对win下java调用命令行操作

基于java17开发,请注意jdk版本

核心功能:

执行基础的命令,建议批量命令写成bat,然后直调用。

public static ExecResult exec(String cmd) {
    //默认30分钟没有输出强行关闭
    return exec(cmd, 30 * 60);
}


public static ExecResult exec(String cmd, int timeout) {
    ExecResult execResult = new ExecResult();

    boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
    if (!isWindows) {
        execResult.setCode(1);
        return execResult;
    }

    try {
        Process process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", cmd});

        DelayTask processDelayTaskTask = new DelayTask<>(process.pid(), timeout * 1000L, process);
        TASK_KILL_QUEUE.put(processDelayTaskTask);

        //执行中的普通输出
        CALLER_RUNS_POLICY_THREAD_POOL.execute(() -> execResult.setResult(getExecResultAndRefresh(process.inputReader(), process, timeout)));

        //执行中的错误输出
        CALLER_RUNS_POLICY_THREAD_POOL.execute(() -> getExecResultAndRefresh(process.errorReader(), process, timeout));

        //阻塞等待结果
        execResult.setCode(process.waitFor());

        TASK_KILL_QUEUE.removeById(processDelayTaskTask.getId());

        return execResult;
    } catch (Exception e) {
        e.printStackTrace();
        execResult.setCode(1);
    }
    return execResult;
}

拓展功能:

有些命令行执行复杂牵扯到第三方调用,可能会卡住(无限期等待),因此需要配置执行超时时间,执行过程中,没有任何输出完全不响应时需要杀掉脚本进程

完整代码:


public class ExecUtils {
    
    private static final AnalogDelayQueue, Long> TASK_KILL_QUEUE = new AnalogDelayQueue<>();

    private static final ThreadPoolExecutor CALLER_RUNS_POLICY_THREAD_POOL = new ThreadPoolExecutor(10, 50, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5), new ThreadPoolExecutor.CallerRunsPolicy());

    private ExecUtils() {
        CALLER_RUNS_POLICY_THREAD_POOL.execute(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    DelayTask delayMessage = TASK_KILL_QUEUE.take();
                    Process process = delayMessage.getData();
                    process.destroy();
                    log.error("触发强制关闭!!!{}", process);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    
    public static ExecResult exec(String cmd) {
        //默认30分钟没有输出强行关闭
        return exec(cmd, 30 * 60);
    }

    
    public static ExecResult exec(String cmd, int timeout) {
        ExecResult execResult = new ExecResult();

        boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
        if (!isWindows) {
            execResult.setCode(1);
            return execResult;
        }

        try {
            Process process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", cmd});

            DelayTask processDelayTaskTask = new DelayTask<>(process.pid(), timeout * 1000L, process);
            TASK_KILL_QUEUE.put(processDelayTaskTask);

            //执行中的普通输出
            CALLER_RUNS_POLICY_THREAD_POOL.execute(() -> execResult.setResult(getExecResultAndRefresh(process.inputReader(), process, timeout)));

            //执行中的错误输出
            CALLER_RUNS_POLICY_THREAD_POOL.execute(() -> getExecResultAndRefresh(process.errorReader(), process, timeout));

            //阻塞等待结果
            execResult.setCode(process.waitFor());

            TASK_KILL_QUEUE.removeById(processDelayTaskTask.getId());

            return execResult;
        } catch (Exception e) {
            e.printStackTrace();
            execResult.setCode(1);
        }
        return execResult;
    }

    
    private static String getExecResultAndRefresh(BufferedReader bufferedReader, Process process, int timeout) {
        try (bufferedReader) {
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                TASK_KILL_QUEUE.rePut(new DelayTask<>(process.pid(), timeout * 1000L, process));

                stringBuilder.append(line).append("n");

                log.info(line);
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
public interface AnalogDelayed extends Delayed {

    
    T getId();
}
public class AnalogDelayQueue, T> extends DelayQueue {

    
    public void rePut(E task) {
        synchronized (this) {
            //如果有对应的delayTask,则将delayTask取出来并从消息队列中移除
            this.removeById(task.getId());
            //放到延时队列
            this.put(task);
        }
    }

    
    public void removeById(T t) {
        super.removeIf(o -> o.getId().equals(t));
    }
}
@Data
@NoArgsConstructor
public class DelayTask implements AnalogDelayed {

    
    private I taskId;

    
    private long time;

    
    private V data;

    
    public DelayTask(I taskId, long millisecond, V data) {
        this.taskId = taskId;
        this.data = data;
        this.time = millisecond + System.currentTimeMillis();
    }

    @Override
    public I getId() {
        return this.taskId;
    }

    
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS) > 0 ? 1 : -1;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979184.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号