如何打开文件

cocotun / 2023-05-13 / 原文

import java.io.File;
import java.awt.Desktop;

public class OpenFileExample {

public static void main(String[] args) {
String filePath = "C:\\Users\\User\\Documents\\example.txt";

File file = new File(filePath);

if (!file.exists() || !file.canRead()) {
System.out.println("无法读取该文件");
return;
}

try {
Desktop desktop = Desktop.getDesktop();
desktop.open(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}