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

有没有一种方法可以将用户的默认浏览器作为String返回?

我正在寻找的例子:

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

您可以使用注册表[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的默认浏览器。

经测试的浏览器:

  • 谷歌浏览器(function返回“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上我认为你可以执行命令xdg-settings get default-web-browser获取默认浏览器。 我可能错了,但也许有权访问这些的人愿意为我测试并评论如何实施它们?