将默认浏览器作为String返回的方法?

时间:2013-04-06 15:53:59

标签: java string browser default

是否有一种方法可以将用户的默认浏览器作为字符串返回?

我正在寻找的例子:

System.out.println(getDefaultBrowser()); // prints "Chrome"

1 个答案:

答案 0 :(得分:21)

您可以使用注册表 [1] 和正则表达式来完成此方法,以将默认浏览器提取为字符串。我知道,没有一种“更清洁”的方法可以做到这一点。

public static String getDefaultBrowser()
{
    try
    {
        // Get registry where we find the default browser
        Process process = Runtime.getRuntime().exec("REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command");
        Scanner kb = new Scanner(process.getInputStream());
        while (kb.hasNextLine())
        {
            // Get output from the terminal, and replace all '\' with '/' (makes regex a bit more manageable)
            String registry = (kb.nextLine()).replaceAll("\\\\", "/").trim();

            // Extract the default browser
            Matcher matcher = Pattern.compile("/(?=[^/]*$)(.+?)[.]").matcher(registry);
            if (matcher.find())
            {
                // Scanner is no longer needed if match is found, so close it
                kb.close();
                String defaultBrowser = matcher.group(1);

                // Capitalize first letter and return String
                defaultBrowser = defaultBrowser.substring(0, 1).toUpperCase() + defaultBrowser.substring(1, defaultBrowser.length());
                return defaultBrowser;
            }
        }
        // Match wasn't found, still need to close Scanner
        kb.close();
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    // Have to return something if everything fails
    return "Error: Unable to get default browser";
}

现在每当调用getDefaultBrowser()时,都应返回Windows的默认浏览器。

经过测试的浏览器:

  • 谷歌浏览器(功能返回“Chrome”)
  • Mozilla Firefox(函数返回“Firefox”)
  • Opera(函数返回“Opera”)

正则表达式(/(?=[^/]*$)(.+?)[.])的解释:

  • /(?=[^/]*$)匹配字符串
  • 中最后发生的/
  • [.]与文件扩展名
  • 中的.相匹配
  • (.+?)捕获这两个匹配字符之间的字符串。

在我们针对正则表达式进行测试之前,您可以通过查看registry的值来了解这是如何捕获的(我已经粗体化了正在捕获的内容):

  

(默认)REG_SZ“C:/ Program Files(x86)/ Mozilla Firefox / firefox .exe”-osint -url“%1”


[1] 仅限Windows。我无法访问Mac或Linux计算机,但是通过环顾互联网,我认为com.apple.LaunchServices.plist将默认浏览器值存储在Mac上,而在Linux上我认为您可以执行命令{{1}获取默认浏览器。我可能错了,但也许有权访问这些的人愿意为我测试并评论如何实施它们?