zoukankan      html  css  js  c++  java
  • 用Java打开一个网页

    BareBonesBrowserLaunch.java

    从网上无意间看到的一个工具类,意思是打开一个URL,在不同的操作系统都通用。

    1.使用

    很简单:

       String url = "http://www.google.com/";         
    BareBonesBrowserLaunch.openURL(url);

    2.下面是BareBonesBrowserLaunch.java 的源码,虽然是别人写的,但看懂了也就成了自己的了。

    /////////////////////////////////////////////////////////
    //Bare Bones Browser Launch //
    //Version 1.5 (December 10, 2005) //
    //By Dem Pilafian //
    //支持: Mac OS X, GNU/Linux, Unix, Windows XP//
    //可免费使用 //
    /////////////////////////////////////////////////////////

    /**
    * @author Dem Pilafian
    * @author John Kristian
    */
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import javax.swing.JOptionPane;

    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 });
    }
    }
    }

  • 相关阅读:
    caffe常用层: batchNorm层和scale层
    简述configure、pkg-config、pkg_config_path三者的关系
    python删除list中元素的三种方法
    Leetcode 872. Leaf-Similar Trees
    Leetcode 508. Most Frequent Subtree Sum
    Leetcode 572. Subtree of Another Tree
    Leetcode 894. All Possible Full Binary Trees
    Leetcode 814. Binary Tree Pruning
    Leetcode 557. Reverse Words in a String III
    python 多维list声明时的小问题
  • 原文地址:https://www.cnblogs.com/u0mo5/p/4071642.html
Copyright © 2011-2022 走看看