syb*_*0rg 17 java browser string default
有没有一种方法可以将用户的默认浏览器作为String返回?
我正在寻找的例子:
System.out.println(getDefaultBrowser()); // prints "Chrome"
Run Code Online (Sandbox Code Playgroud)
syb*_*0rg 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";
}
Run Code Online (Sandbox Code Playgroud)
现在无论何时getDefaultBrowser()
调用,都应该返回Windows的默认浏览器.
经测试的浏览器:
正则表达式(/(?=[^/]*$)(.+?)[.]
)的解释:
/(?=[^/]*$)
匹配/
字符串中的最后一个[.]
匹配.
文件扩展名(.+?)
捕获这两个匹配字符之间的字符串.registry
在我们针对正则表达式进行测试之前,你可以通过查看右边的值来了解如何捕获它(我已经粗体化了所捕获的内容):
(默认)REG_SZ"C:/ Program Files(x86)/ Mozilla Firefox/firefox .exe"-osint -url"%1"
[1]仅限Windows.我无法访问Mac或Linux计算机,但是通过com.apple.LaunchServices.plist
浏览Internet,我认为在Mac上存储默认浏览器值,而在Linux上我认为您可以执行命令xdg-settings get default-web-browser
来获取默认浏览器.我可能错了,但也许有权访问这些的人愿意为我测试并评论如何实施它们?