You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java调用Mac命令行获取Edge/Chrome浏览器版本报错如何解决

问题原因

Runtime.getRuntime().exec(String command) 方法没有Shell解析能力,只会简单按照空白字符拆分命令片段。Edge、Chrome的安装路径包含空格(Microsoft Edge、Google Chrome),会被拆成多个独立的命令片段,导致系统识别执行路径时只读到空格前的部分,触发找不到文件的报错。
你手动添加的引号、空格转义符在该方法中只会被识别为普通字符,不会起到合并带空格路径的作用,这就是为什么打印出来的命令复制到终端(Shell环境会解析引号和转义)可正常运行,Java调用却报错的原因。

解决方法

使用接收字符串数组参数的exec重载方法,将可执行文件完整路径、命令参数拆分为独立元素传入即可,不需要给路径额外加引号或转义空格。

示例代码

import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BrowserVersionTest {
    public static void main(String[] args) throws Exception {
        String line;
        Process process;
        String browserVersion = null;

        // 获取Edge版本
        String[] edgeCmd = {"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", "-version"};
        // 获取Chrome版本 替换上面的edgeCmd即可
        // String[] chromeCmd = {"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "--version"};
        // 获取Firefox版本 替换上面的edgeCmd即可
        // String[] firefoxCmd = {"/Applications/Firefox.app/Contents/MacOS/firefox", "-v"};
        
        process = Runtime.getRuntime().exec(edgeCmd);
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while ((line = br.readLine()) != null) {
            if (!StringUtils.isBlank(line)) {
                browserVersion = line;
                System.out.println(browserVersion);
            }
        }
        process.waitFor();
        process.destroy();
    }
}

内容的提问来源于stack exchange,提问作者Sadanand Kolhe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:27:04