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



我有一个简单的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());
}
}
}

我希望找到一个解决方案

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

我不能访问MacOS和linux,所以我不能评论它们。

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

在Windows上,为了启动默认的Internet浏览器,您可以使用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。