繁体   English   中英

在 Eclipse 上使用 Java 在默认浏览器中打开 URL 时遇到问题

[英]Facing issues while opening a URL in the default browser using Java on Eclipse

我有一个简单的Java 程序我想做的是在我的操作系统的默认浏览器中打开一个URL例如“https://github.com”在我的例子中,我使用Windows 10

这是我在eclipse上运行程序时得到的结果:

图片

我认为我的代码有问题:

package com.main;

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

public class Browser {
    public void displayURL() throws Exception {

        String url = "https://github.com";
        String myOS = System.getProperty("os.name").toLowerCase();
        System.out.println("(Your operating system is: " + myOS + ")\n");

        try {
            if (Desktop.isDesktopSupported()) {
                System.out.println(" -- Going with Desktop.browse ...");
                Desktop desktop = Desktop.getDesktop();
                desktop.browse(new URI(url));
            } else {
                ProcessBuilder pb = new ProcessBuilder();
                if (myOS.contains("windows 10")) {
                    System.out.println("Hello Windows 10");
                    pb.command("start " + url);
                    pb.start();
                } else if (myOS.contains("mac")) {
                    pb.command("open " + url);
                    pb.start();
                } else if (myOS.contains("nix") || myOS.contains("nux")) {
                    pb.command("xdg-open " + url);
                    pb.start();
                } else {
                    System.out.println("Sorry!! I could not launch the browser on your operating system.");
                }
            }
        } catch (Exception e) {
            System.out.println("Oops!! Something is wrong. " + e.getMessage());
        }
    }
}

我希望找到解决办法

Class java.lang.ProcessBuilder用于启动可执行文件。

我无法访问 MacOS 和 linux,所以我无法对它们发表评论。

对于 Windows, start不是可执行文件,它是cmd.exe的内部命令(就像dir一样)。 因此,您收到错误消息。 Java 正在寻找名为start的可执行文件,但找不到。

在 Windows 上,为了启动默认的 Inte.net 浏览器,您可以使用rundll32.exe

import java.io.IOException;

public class Browser {

    public static void main(String[] args) {
        ProcessBuilder pb = new ProcessBuilder("rundll32.exe",
                                               "url.dll,OpenURL",
                                               "https://github.com");
        try {
            pb.start();
        }
        catch (IOException x) {
            x.printStackTrace();
        }
    }
}

当我运行上面的代码时,它会在 GitHub 主页上启动Microsoft Edge

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM