自 JDK 1.6 起,Java 新增 java.awt.Desktop 類,允許應用程序啟動本地桌面註冊的關聯程序來處理 URI 或文件。它封裝了跨平台的本地操作,無需依賴 JNI 或第三方庫,極大簡化了桌面集成開發。
package com.brucezhang.desktop;
import java.awt.Desktop;
import java.io.File;
import java.net.URI;
public class DeskTopTest {
private static Desktop desktop;
// 1. 打開網頁
public static void browse() {
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
try {
desktop.browse(new URI("https://blog.csdn.net/dlutbrucezhang?viewmode=contents"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 2. 編輯文件
public static void edit() {
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
try {
desktop.edit(new File("D:\\BruceZhang.txt"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 3. 打開文件
public static void open() {
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
try {
desktop.open(new File("D:\\BruceZhang.txt"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 4. 打印文件
public static void print() {
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
try {
desktop.print(new File("D:\\BruceZhang.txt"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
browse();
edit();
open();
print();
}
}
Desktop.isDesktopSupported() 判斷當前平台是否支持,避免無頭服務器或精簡版 Linux 拋出異常。IOException 或 URISyntaxException,需妥善捕獲。注意:Desktop 僅適用於桌面環境,無法在無界面服務器或 Android 等非標準桌面平台使用。Web 應用中請勿直接調用。