首页 > 解决方案 > 使用 java 的命令行方法进行浏览器版本检测

问题描述

我知道使用在我的系统上正常工作的命令行在 mac中获取 Edge、Firefox 和 Chrome 的浏览器版本的命令。Edge=/Applications/"Microsoft Edge.app"/Contents/MacOS/"Microsoft Edge" -version FireFox=/Applications/Firefox.app/Contents/MacOS/firefox -v Chrome=/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version

Chrome1=/Applications/"Google Chrome.app"/Contents/MacOS/"Google Chrome" --version

当我尝试使用 Firefox 时,它成功地返回了 Firefox 版本。但是当我尝试使用 Edge 或 chrome 时,它​​会在 java 程序中引发错误。

无法运行程序 "/Application/"Google" 错误=2 没有这样的文件或目录

我尝试将查询转义为/Applications/\"Microsoft Edge.app\"/Contents/MacOS/\"Microsoft Edge\" -version。我在作为查询传递之前打印相同的查询,如果我直接将其复制粘贴到终端上,我将得到完全相同的查询。

下面是代码片段

我错过了什么吗?

    String line;
            Process process;
            String msEdgeVersion = null;
    
            /*process = Runtime.getRuntime().exec("/Applications/Firefox.app/Contents/MacOS/firefox -v");*/
    
            process = Runtime.getRuntime().exec(/Applications/"Microsoft Edge.app"/Contents/MacOS/"Microsoft Edge" -version);
    
            // process = Runtime.getRuntime().exec("where notepad");
    
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = br.readLine()) != null) {
                if (!StringUtils.isBlank(line)) {
                    msEdgeVersion = line;
                    System.out.println(line);
                }
            }
            process.waitFor();
            process.destroy();

标签: macosgoogle-chromefirefoxcommand-linemicrosoft-edge

解决方案


根据相关api Runtime.getRuntime().exec(String command),需要知道传入的参数是合法的 String,所以需要注意String参数类型的格式。

编辑

我重现了您的问题并遇到了同样的问题。经过搜索,我发现了同样的问题。这是因为 Process 不同于终端进程。您必须添加-l以登录用户身份运行命令。

这是我的测试: 在此处输入图像描述


推荐阅读