java Runtime.getRuntime().exec

记录几个用法。

    final static boolean IS_WIN = System.getProperty("os.name").toLowerCase().contains("win");
    final static boolean IS_OSX = System.getProperty("os.name").toLowerCase().contains("mac");
    final static boolean IS_LINUX = !IS_WIN && !IS_OSX;
   
    从终端中输入echo $PATH 或者 /usr/bin/env 输入的结果填入。
    final static String[] SystemEnvp = new String[] {"PATH=/opt/homebrew/bin:/opt/homebrew/sbin:/Users/allan/Library/Android/sdk/platform-tools:/Users/allan/bin:/Users/allan/Documents/jdk1.8.0.322aarch64_zulu/zulu-8.jdk/Contents/Home/bin:/opt/homebrew/opt/grep/libexec/gnubin:/opt/homebrew/opt/gnu-tar/libexec/gnubin:/opt/homebrew/opt/coreutils/libexec/gnubin:/opt/homebrew/opt/gnu-sed/libexec/gnubin:/opt/homebrew/opt/findutils/libexec/gnubin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin"};


public static List<String> runBig(String command, boolean printLog) {
        System.out.println("[cmd]: " + command);
        String[] cmdArr = new String[3];
        cmdArr[0] = IS_WIN ? "cmd" : "/bin/sh";
        cmdArr[1] = IS_WIN ? "/c" : "-c";
        cmdArr[2] = command;

        final List<String> results = new ArrayList<>();
        final Process process;
        final BufferedReader bufrIn;
        final BufferedReader bufrError;
        // 执行命令, 返回一个子进程对象(命令在子进程中执行
        try {
            process = Runtime.getRuntime().exec(cmdArr, SystemEnvp);
            // 方法阻塞, 等待命令执行完成(成功会返回0)
            bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8));
            new Thread(()-> {
                // 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出(PS: 子进程的输出就是主进程的输入)
                // 读取输出
                String line;
                try {
                    while ((line = bufrIn.readLine()) != null) {
                        if(printLog) System.out.println("[cmd]: " + line);
                        results.add(line);
                    }
                    while ((line = bufrError.readLine()) != null) {
                        if(printLog) System.out.println("[cmd]: " + line);
                        results.add(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("似乎读取有点小问题了。");
                } finally {
                    closeStream(bufrError);
                    closeStream(bufrIn);
                    // 销毁子进程
                    process.destroy();
                }
            }).start();
            int status = process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            //result.setLength(0);
        }
        return results;
    }

关键点2个参数:
第一个参数cmd,使用数组来包装command,而不是直接跟一串空格的命令。
第二个参数envp,一般我们都没有调用过。最近遇到了一个难题,在java代码中,通过Runtime执行shell脚本,而shell脚本却无法类似终端里面,正确执行。
这是因为缺失环境变量导致。

在mac/linux(win未验证估计一样)上,主要是缺少正确的PATH。
可以通过执行runBig(“java -version”, false);
或者runBig("/usr/bin/env", false);
同时在终端里面,敲入java -version。/usr/bin/env。就可以看出你的环境变量可能是没有弄到idea中。

另外,新电脑,给bashrc配置了环境,需要重启电脑。否则,terminal能执行脚本了,是因为他加载了bashrc,而系统没有运行就没法给IDEA等加载环境。
当你正确配置以后,重启电脑,java代码中的环境变量也可以改成null了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值