如何使用java打开默认Web浏览器

时间:2011-03-07 22:48:15

标签: java

有人可以指出我正确的方向如何打开默认网络浏览器并将页面设置为“www.example.com”谢谢

9 个答案:

答案 0 :(得分:135)

java.awt.Desktop是您正在寻找的课程。

import java.awt.Desktop;
import java.net.URI;

// ...

if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
    Desktop.getDesktop().browse(new URI("http://www.example.com"));
}

答案 1 :(得分:33)

这是我的代码。它将在默认浏览器(跨平台解决方案)中打开给定URL。

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class Browser {
    public static void main(String[] args) {
        String url = "http://www.google.com";

        if(Desktop.isDesktopSupported()){
            Desktop desktop = Desktop.getDesktop();
            try {
                desktop.browse(new URI(url));
            } catch (IOException | URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("xdg-open " + url);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

答案 2 :(得分:28)

对于我来说,使用Desktop.isDesktopSupported()的解决方案不起作用(Windows 7和ubuntu)。请尝试从java代码打开浏览器:

Windows:

Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("rundll32 url.dll,FileProtocolHandler " + url);

的Mac

Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("open " + url);

Linux的:

Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
String[] browsers = { "epiphany", "firefox", "mozilla", "konqueror",
                                 "netscape", "opera", "links", "lynx" };

StringBuffer cmd = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
    if(i == 0)
        cmd.append(String.format(    "%s \"%s\"", browsers[i], url);
    else
        cmd.append(String.format(" || %s \"%s\"", browsers[i], url); 
    // If the first didn't work, try the next browser and so on

rt.exec(new String[] { "sh", "-c", cmd.toString() });

如果您想拥有多平台应用程序,则需要添加操作系统检查(例如):

String os = System.getProperty("os.name").toLowerCase();

视窗:

os.indexOf("win") >= 0

的Mac:

os.indexOf("mac") >= 0

Linux的:

os.indexOf("nix") >=0 || os.indexOf("nux") >=0

答案 3 :(得分:7)

您还可以使用运行时来创建跨平台解决方案:

import java.awt.Desktop;
import java.net.URI;

public class App {

    public static void main(String[] args) throws Exception {
        String url = "http://stackoverflow.com";

        if (Desktop.isDesktopSupported()) {
            // Windows
            Desktop.getDesktop().browse(new URI(url));
        } else {
            // Ubuntu
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("/usr/bin/firefox -new-window " + url);
        }
    }
}

答案 4 :(得分:5)

正如Tim Cooper提供的答案所述,java.awt.Desktop自Java版本6(1.6)以来提供了此功能,但有以下警告:

  

Use the isDesktopSupported() method to determine whether the Desktop API is available. On the Solaris Operating System and the Linux platform, this API is dependent on Gnome libraries. If those libraries are unavailable, this method will return false.

对于不支持或提供java.awt.Desktop的平台,请查看BrowserLauncher2项目。它是由Eric Albert最初编写和发布的BrowserLauncher类派生而来的。我在一个多平台Java应用程序中成功使用了原始的BrowserLauncher类,该应用程序在21世纪初期通过Web浏览器界面在本地运行。

请注意,BrowserLauncher2已获得GNU Lesser General Public License许可。如果该许可证是不可接受的,请查找原始BrowserLauncher的副本,该副本具有非常宽松的许可证:

  

此代码为Eric Albert(ejalbert@cs.stanford.edu)版权所有1999-2001,并且可以不受任何形式重新分发或修改,只要本段中的评论部分到评论结尾没有删除。作者要求他通知任何使用此代码的应用程序,applet或其他二进制文件,但这更多地出于好奇而不是任何需要。本软件不含保修。对于因使用本软件而造成的任何数据或功能损失或任何不利或意外影响,作者不予以回应。

     

现金:   JavaWorld杂志的Steven Spencer(Java技巧66)   还要感谢Ron B. Yeh,Eric Shapiro,Ben Engber,Paul Teitlebaum,Andrea Cantatore,Larry Barowski,Trevor Bedzek,Frank Miedrich和Ron Rabakukk

自2001年以来,BrowserLauncher2以外的项目可能还更新了原始的BrowserLauncher,以说明浏览器和默认系统安全设置的变化。

答案 5 :(得分:3)

它非常简单,只需编写下面的代码:

String s = "http://www.google.com";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));

或者如果您不想加载URL,则只需将浏览器名称写入字符串值,例如

String s = "chrome";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));

执行程序

后会自动打开浏览器并显示空URL

答案 6 :(得分:1)

Windows上的

调用“cmd / k start http://www.example.com” 事实上,您始终可以使用start命令调用“默认”程序。 对于ex start,abc.mp3将调用默认的mp3播放器并加载所请求的mp3文件。

答案 7 :(得分:1)

希望您不介意,但我从上面将所有有用的东西拼凑在一起,并准备了完整的课程来进行测试...

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class MultiBrowPop {

    public static void main(String[] args) {
        OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");

        String url = "http://www.birdfolk.co.uk/cricmob";
        OUT("We're going to this page: "+ url);

        String myOS = System.getProperty("os.name").toLowerCase();
        OUT("(Your operating system is: "+ myOS +")\n");

        try {
            if(Desktop.isDesktopSupported()) { // Probably Windows
                OUT(" -- Going with Desktop.browse ...");
                Desktop desktop = Desktop.getDesktop();
                desktop.browse(new URI(url));
            } else { // Definitely Non-windows
                Runtime runtime = Runtime.getRuntime();
                if(myOS.contains("mac")) { // Apples
                    OUT(" -- Going on Apple with 'open'...");
                    runtime.exec("open " + url);
                } 
                else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours 
                    OUT(" -- Going on Linux with 'xdg-open'...");
                    runtime.exec("xdg-open " + url);
                }
                else 
                    OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
            }
            OUT("\nThings have finished.\nI hope you're OK.");
        }
        catch(IOException | URISyntaxException eek) {
            OUT("**Stuff wrongly: "+ eek.getMessage());
        }
    }

    private static void OUT(String str) {
        System.out.println(str);
    }
}

答案 8 :(得分:0)

我将Brajesh Kumar的回答改写成Clojure,如下所示:

(defn open-browser 
  "Open a new browser (window or tab) viewing the document at this `uri`."
  [uri]
  (if (java.awt.Desktop/isDesktopSupported)
    (let [desktop (java.awt.Desktop/getDesktop)]
      (.browse desktop (java.net.URI. uri)))
    (let [rt (java.lang.Runtime/getRuntime)]
      (.exec rt (str "xdg-open " uri)))))

以防对任何人有用。