J2SE 6 新增了 java.awt.Desktop ,这套桌面 API 使用你的主机操作系统的文件关联以启动与特定文件类型相关联的应用程序。调用本地浏览器非常方便,且跨平台适用。
1public static void runBroswer(String webSite) {
2 try {
3 Desktop desktop = Desktop.getDesktop();
4 if (desktop.isDesktopSupported() && desktop.isSupported(Desktop.Action.BROWSE)){
5 URI uri = new URI(webSite);
6 desktop.browse(uri);
7 }
8 } catch (IOException ex) {
9 ex.printStackTrace();
10 } catch (URISyntaxException ex) {
11 ex.printStackTrace();
12 }
13}
J2SE 5及之前可使用以下代码
1public static void openURL(String url) {
2 String osName = System.getProperty("os.name");
3 try {
4 if (osName.startsWith("Mac")) {//Mac OS
5 Class fileMgr = Class.forName("com.apple.eio.FileManager");
6 Method openURL = fileMgr.getDeclaredMethod("openURL",new Class[]{String.class});
7 openURL.invoke(null, new Object[]{url});
8 } else if (
9 osName.startsWith("Windows")){//Windows
10 Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
11 } else { //Unix or Linux
12 String[] browsers = {"firefox", "opera", "konqueror",
13 "epiphany", "mozilla", "netscape"};
14 String browser = null;
15 for (int count = 0; count < browsers.length && browser == null; count++) {
16 if (Runtime.getRuntime().exec(
17new String[]{"which", browsers[count]}).waitFor() == 0) {
18 browser = browsers[count];
19 }
20 }
21 if (browser == null) {
22 throw new Exception("Could not find web browser");
23 } else {
24 Runtime.getRuntime().exec(new String[]{browser, url});
25 }
26 }
27 } catch (Exception ex) {
28 ex.printStackTrace();
29 }
30}
31
本文来自CSDN博客,转载请标明出处:
http://blog.csdn.net/casularm/archive/2008/11/28/3401018.aspx