用Java打開一個網頁


BareBonesBrowserLaunch.java

從網上無意間看到的一個工具類,意思是打開一個URL,在不同的操作系統都通用。

1.使用

很簡單:

Java代碼 
1   String url = "http://www.google.com/";         
2 BareBonesBrowserLaunch.openURL(url);

2.下面是BareBonesBrowserLaunch.java 的源碼,雖然是別人寫的,但看懂了也就成了自己的了。

Java代碼 
 1 /////////////////////////////////////////////////////////  
2 //Bare Bones Browser Launch //
3 //Version 1.5 (December 10, 2005) //
4 //By Dem Pilafian //
5 //支持: Mac OS X, GNU/Linux, Unix, Windows XP//
6 //可免費使用 //
7 /////////////////////////////////////////////////////////
8
9 /**
10 * @author Dem Pilafian
11 * @author John Kristian
12 */
13 import java.io.IOException;
14 import java.lang.reflect.InvocationTargetException;
15 import java.lang.reflect.Method;
16 import javax.swing.JOptionPane;
17
18 public class BareBonesBrowserLaunch {
19
20 public static void openURL(String url) {
21 try {
22 browse(url);
23 } catch (Exception e) {
24 }
25 }
26
27 private static void browse(String url) throws Exception {
28 //獲取操作系統的名字
29 String osName = System.getProperty("os.name", "");
30 if (osName.startsWith("Mac OS")) {
31 //蘋果的打開方式
32 Class fileMgr = Class.forName("com.apple.eio.FileManager");
33 Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });
34 openURL.invoke(null, new Object[] { url });
35 } else if (osName.startsWith("Windows")) {
36 //windows的打開方式。
37 Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
38 } else {
39 // Unix or Linux的打開方式
40 String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
41 String browser = null;
42 for (int count = 0; count < browsers.length && browser == null; count++)
43 //執行代碼,在brower有值后跳出,
44 //這里是如果進程創建成功了,==0是表示正常結束。
45 if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)
46 browser = browsers[count];
47 if (browser == null)
48 throw new Exception("Could not find web browser");
49 else
50 //這個值在上面已經成功的得到了一個進程。
51 Runtime.getRuntime().exec(new String[] { browser, url });
52 }
53 }
54 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM