java 打开网页

来源:互联网 发布:android ndk linux 32 编辑:程序博客网 时间:2024/06/04 21:02

http://www.cnblogs.com/ayan/archive/2011/12/29/2306805.html


从网上无意间看到的一个工具类,意思是打开一个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 }  
复制代码

原创粉丝点击