Apache Commons Exec 简介

Apache Commons Exec 是 Apache Commons 下面的一个子项目,它提供一些常用的方法用来执行外部进程。

在实际开发项目中,有时候我们可能需要使用 java 去调用外部的进程,例如:调用 cmd.exe 去执行命令,获取主板、CPU等信息,或打开浏览器、记事本、计算器等等。

通常,我们可以直接使用 Runtime.getRuntime().exec() 方法去执行外部进程,例如:通过 Runtime.getRuntime().exec() 打开计算器,代码如下:

/**
 * 使用 Runtime.getRuntime().exec() 打开计算器
 * @author hxstrive.com 2021/12/23
 */
public class Demo1 {
    public static void main(String[] args) throws Exception {
        Runtime.getRuntime().exec("calc.exe");
    }
}

上面代码在 Windows 系统中运行正常,在其他系统中运行会失败。因此,需要我们自己去适配不同的操作系统。做起来太麻烦,而且要做的完成正确不容易。正因为这些问题,笔者推荐使用 Apache Commons Exec 库去执行外部进程。

Apache Commons Exec 是 Apache Commons 下面的一个子项目,它提供一些常用的方法用来执行外部进程。Apache Commons Exec 库提供了监视狗 Watchdog 来设监视进程的执行超时,同时也还实现了同步和异步功能。

同时,它也涉及到多线程,比如新启动一个进程,Java 中需要再开三个线程来处理进程的三个数据流,分别是标准输入,标准输出和错误输出。

Apache Commons Exec 示例

引入依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-exec</artifactId>
    <version>1.3</version>
</dependency>

Java 代码

下面代码,将使用 Apache Commons Exec 去打开计算器,代码如下:

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;

/**
 * 使用 commons exec 打开计算器
 * @author hxstrive.com 2021/12/23
 */
public class Demo2 {

    public static void main(String[] args) throws Exception {
        // 定义一个命令行
        CommandLine cmdLine = CommandLine.parse("calc.exe");
        // 默认执行器
        DefaultExecutor executor = new DefaultExecutor();
        // 使用执行器执行命令行
        int exitValue = executor.execute(cmdLine);
        if(exitValue == 0) {
            System.out.println("执行成功, exitValue=" + exitValue);
        } else {
            System.err.println("执行失败, exitValue=" + exitValue);
        }
    }

}
不是每一次努力都有收获,但是,每一次收获都必须努力。
0 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号