问题
有人可以指出我正确的方向如何打开默认的网络浏览器并将页面设置为**"www.example.com"**感谢
#1 热门回答(119 赞)
java.awt.Desktop是你要找的班级。
import java.awt.Desktop;
import java.net.URI;
// ...
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(new URI("http://www.example.com"));
}
#2 热门回答(33 赞)
这是我的代码。它将在默认浏览器(跨平台解决方案)中打开给定URL。
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Browser {
public static void main(String[] args) {
String url = "http://www.google.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#3 热门回答(25 赞)
对我来说,使用Desktop.isDesktopSupported()的解决方案不起作用(Windows 7和ubuntu)。请尝试从java代码打开浏览器:
视窗:
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 = { "epiphany", "firefox", "mozilla", "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