在 Java 應用程式中,有時需要直接啟動系統預設瀏覽器或指定瀏覽器(如 IE)來開啟特定 URL。常見的做法有兩種:一是透過 Runtime.exec() 執行命令列指令,二是使用 java.awt.Desktop 類別的 browse() 方法。下面分別說明這兩種方式的程式碼範例與注意事項。
這種方式直接呼叫作業系統的命令列,透過 cmd /c start iexplore <URL> 來啟動 Internet Explorer。雖然直觀,但具有平台相依性,僅適用於 Windows 環境且需確認 IE 路徑在環境變數中。
String url = "https://blog.csdn.net/powmxypow";
String cmd = "cmd /c start iexplore " + url;
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
e.printStackTrace();
}
java.awt.Desktop 是 Java 6 引入的跨平台 API,能自動啟動系統預設瀏覽器開啟 URI。程式碼更簡潔、可移植性更好,是現代 Java 專案的首選。
String url = "https://blog.csdn.net/powmxypow";
try {
URI uri = new URI(url);
Desktop.getDesktop().browse(uri);
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
package test.com;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class OpenUrlDemo {
public static void main(String[] args) {
String targetUrl = "https://blog.csdn.net/powmxypow";
// 方式一:指定啟動 IE(僅限 Windows)
String cmd = "cmd /c start iexplore " + targetUrl;
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
System.err.println("啟動 IE 失敗:" + e.getMessage());
}
// 方式二:使用系統預設瀏覽器(跨平台)
try {
Desktop.getDesktop().browse(new URI(targetUrl));
} catch (URISyntaxException | IOException e) {
System.err.println("啟動預設瀏覽器失敗:" + e.getMessage());
}
}
}
Desktop 類別需要圖形化環境支援,在無頭伺服器上可能拋出 UnsupportedOperationException。