如何使用java打开默认的Web浏览器

2022-08-31 08:26:48

有人可以给我指出正确的方向,如何打开默认的Web浏览器并将页面设置为“www.example.com”谢谢


答案 1

java.awt.Desktop是你要找的类。

import java.awt.Desktop;
import java.net.URI;

// ...

if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
    Desktop.getDesktop().browse(new URI("http://www.example.com"));
}

答案 2

对我来说,解决方案不起作用(Windows 7ubuntu)。请尝试从java代码打开浏览器:Desktop.isDesktopSupported()

窗户:

Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("rundll32 url.dll,FileProtocolHandler " + url);

苹果电脑

Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("open " + url);

Linux:

Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
String[] browsers = { "google-chrome", "firefox", "mozilla", "epiphany", "konqueror",
                                 "netscape", "opera", "links", "lynx" };
 
StringBuffer cmd = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
    if(i == 0)
        cmd.append(String.format(    "%s \"%s\"", browsers[i], url));
    else
        cmd.append(String.format(" || %s \"%s\"", browsers[i], url)); 
    // If the first didn't work, try the next browser and so on

rt.exec(new String[] { "sh", "-c", cmd.toString() });

如果你想有多平台应用,你需要添加操作系统检查(例如):

String os = System.getProperty("os.name").toLowerCase();

窗户:

os.indexOf("win") >= 0

苹果电脑:

os.indexOf("mac") >= 0

Linux:

os.indexOf("nix") >=0 || os.indexOf("nux") >=0

推荐