用Java開啟一個網頁

來源:互聯網
上載者:User
文章目錄
  • 1.使用
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 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.