我有一个简单的Java程序,我想做的是在我的操作系统上的默认浏览器中打开一个URL例如“https://github.com“*。在我的情况下,我使用Windows 10。
下面是我在eclipse上运行程序时得到的结果:
Image
我觉得我的代码有问题:
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());
}
}
}
我希望能找到解决办法
1条答案
按热度按时间yvt65v4c1#
类java.lang.ProcessBuilder用于启动可执行文件。
我既不能访问MacOS也不能访问Linux,所以我不能对它们发表评论。
对于Windows,
start
不是一个可执行文件,它是cmd.exe的内部命令(就像dir
一样)。因此您会收到错误消息。Java正在查找名为start
的可执行文件,但找不到。在Windows上,为了启动默认的Internet浏览器,可以使用rundll32.exe。
当我运行上面的代码时,它会在GitHub主页上启动Microsoft Edge。