当前位置: 移动技术网 > IT编程>开发语言>Java > java程序中指定某个浏览器打开的实现方法

java程序中指定某个浏览器打开的实现方法

2019年07月22日  | 移动技术网IT编程  | 我要评论
本文主要介绍的是利用java程序打开指定某个的浏览器,文中分享了四种实现方法,感兴趣的朋友们下面来一起看看吧。 方法一: package com.test;

本文主要介绍的是利用java程序打开指定某个的浏览器,文中分享了四种实现方法,感兴趣的朋友们下面来一起看看吧。

方法一:

package com.test;
 
import java.lang.reflect.method;
 
//实现打开浏览器并跳到指定网址的类
public class barebonesbrowserlaunch {
 public static void openurl(string url) { 
  try { 
   browse(url); 
  } catch (exception e) { 
  } 
 } 
 
 private static void browse(string url) throws exception { 
  //获取操作系统的名字 
  string osname = system.getproperty("os.name", ""); 
  if (osname.startswith("mac os")) { 
   //苹果的打开方式 
   class filemgr = class.forname("com.apple.eio.filemanager"); 
   method openurl = filemgr.getdeclaredmethod("openurl", new class[] { string.class }); 
   openurl.invoke(null, new object[] { url }); 
  } else if (osname.startswith("windows")) { 
   //windows的打开方式。 
   runtime.getruntime().exec("rundll32 url.dll,fileprotocolhandler " + url); 
  } else { 
   // unix or linux的打开方式 
   string[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" }; 
   string browser = null; 
   for (int count = 0; count < browsers.length && browser == null; count++) 
    //执行代码,在brower有值后跳出, 
    //这里是如果进程创建成功了,==0是表示正常结束。 
    if (runtime.getruntime().exec(new string[] { "which", browsers[count] }).waitfor() == 0) 
     browser = browsers[count]; 
   if (browser == null) 
    throw new exception("could not find web browser"); 
   else 
    //这个值在上面已经成功的得到了一个进程。 
    runtime.getruntime().exec(new string[] { browser, url }); 
  } 
 } 
}
 
//主方法 测试类
public static void main(string[] args) {
 // 这里填写你的网址
 string url = "xxx";   
 barebonesbrowserlaunch.openurl(url); 
}

方法二:

使用默认浏览器打开:

 string site = "www.baidu.com";
 try {
  desktop desktop = desktop.getdesktop();
  if (desktop.isdesktopsupported() && desktop.issupported(desktop.action.browse)) {
   uri uri = new uri(site);
   desktop.browse(uri);
  }
 } catch (ioexception ex) {
  system.out.println(ex);
 } catch (urisyntaxexception ex) {
  system.out.println(ex);
 }

方法三:

通过获取环境变量的浏览器路径,然后启动浏览器

string firefox="c:\\program files\\mozilla firefox\\firefox.exe";
    map map = system.getenv();
    for(iterator itr = map.keyset().iterator();itr.hasnext();){
     string value = (string)map.get((string)itr.next());
     if (value.contains("firefox.exe")) {
      firefox=value;
      break;
    }
    } 
     runtime.getruntime().exec(new string[] {firefox, "www.baidu.com" });

方法四:

js方式:

<script type="text/javascript">
window.onload=function(){
var wsh = new activexobject("wscript.shell"); 
  wsh.run("chrome.exe www.baidu.com"); 
}
 
</script>

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网