Java调用浏览器

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" ,  
  7.                         new  Class[]{String. class });  
  8.                 openURL.invoke(nullnew  Object[]{url});  
  9.             } else   if  (osName.startsWith( "Windows" )) { //Windows   
  10.                 Runtime.getRuntime().exec(  
  11.                         "rundll32 url.dll,FileProtocolHandler "  + url);  
  12.             } else  {    //Unix   or   Linux   
  13.                 String[] browsers = {"firefox""opera""konqueror" ,  
  14.                     "epiphany""mozilla""netscape" };  
  15.                 String browser = null ;  
  16.                 for  ( int  count =  0 ; count < browsers.length && browser ==  null ; count++) {  
  17.                     if  (Runtime.getRuntime().exec(  
  18.                             new  String[]{ "which" , browsers[count]}).waitFor() ==  0 ) {  
  19.                         browser = browsers[count];  
  20.                     }  
  21.                 }  
  22.                 if  (browser ==  null ) {  
  23.                     throw   new  Exception( "Could not find web browser" );  
  24.                 } else  {  
  25.                     Runtime.getRuntime().exec(new  String[]{browser, url});  
  26.                 }  
  27.             }  
  28.         } catch  (Exception ex) {  
  29.             ex.printStackTrace();  
  30.         }  
  31.     }  

如果是Applet则用以下代码直接访问链接

  1. AppletContext context = getAppletContext();  
  2. context.showDocument(new  URL( "http://blog.youkuaiyun.com/casularm" ),  "_blank" ); 
原文地址:http://blog.youkuaiyun.com/casularm/archive/2008/11/28/3401018.aspx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值