java webbrowser,如何使用java打开默认的webbrowser

问题

有人可以指出我正确的方向如何打开默认的网络浏览器并将页面设置为**"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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值