J2SE 6 新增了 java.awt.Desktop ,這套桌面 API 使用你的主機操作系統的文件關聯以啟動與特定文件類型相關聯的應用程序。調用本地瀏覽器非常方便,且跨平臺適用。
1
public 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及之前可使用以下代碼
1
public 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(
17
new 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