我正在尝试使用JavaFx在按钮单击事件中打开文件。
java.awt.Desktop.getDesktop().open(File f);
但它在java.awt.Desktop.getDesktop 异常中给出了 java.awt.HeadlessException。
有什么方法可以在无头环境中打开文件吗?
答案 0 :(得分:1)
一种尝试是暂时禁用无头,打开文件,然后再次启用它。像这样:
System.setProperty("java.awt.headless", "true"); // assume it is enabled somewhere
File desktop = new File(System.getProperty("user.home"), "Desktop");
File text = new File(desktop, "a.txt");
System.setProperty("java.awt.headless", "false");
Desktop.getDesktop().open(text);
System.setProperty("java.awt.headless", "true");
但是,有时System.setProperty("java.awt.headless", "false");
不足以禁用无头财产。一种 dirty 解决方案是通过reflect
更改其值。
System.setProperty("java.awt.headless", "true"); // assume it is enabled somewhere
File desktop = new File(System.getProperty("user.home"), "Desktop");
File text = new File(desktop, "a.txt");
setHeadless(false);
Desktop.getDesktop().open(text);
setHeadless(true);
Desktop.getDesktop().open(text);
使用setHeadless
方法:
private static void setHeadless(boolean enabled) {
try {
Field defaultHeadlessField = java.awt.GraphicsEnvironment.class.getDeclaredField("defaultHeadless");
defaultHeadlessField.setAccessible(true);
defaultHeadlessField.set(null, enabled);
Field headlessField = java.awt.GraphicsEnvironment.class.getDeclaredField("headless");
headlessField.setAccessible(true);
headlessField.set(null, enabled);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
第二次尝试(还有更多的“强制”)是通过命令行打开它。对于 Windows 操作系统(我不知道 Linux / MacOS )是:
File desktop = new File(System.getProperty("user.home"), "Desktop");
File text = new File(desktop, "a.txt");
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("cmd.exe", "/c", text.getAbsolutePath()).start();