当我开发基于桌面的应用程序时,有一个.pdf格式的用户手册,在用户单击帮助菜单项时应该打开该手册。如何在java中打开.pdf文件
我不知道从swing应用程序打开.pdf文件的方式,所以我如何在我的jframe
或任何pdf文件查看器(如acrobat reader)中打开它。
当我开发基于桌面的应用程序时,有一个.pdf格式的用户手册,在用户单击帮助菜单项时应该打开该手册。如何在java中打开.pdf文件
我不知道从swing应用程序打开.pdf文件的方式,所以我如何在我的jframe
或任何pdf文件查看器(如acrobat reader)中打开它。
尝试使用此Runtime.getRuntime().exec("cmd PDF_FILE")
。这将在Acrobat Reader中打开pdf,就像双击该文件一样。
Desktop desktop = Desktop.getDesktop();
File file = new File(path);
desktop.open(file);
将打开系统默认浏览器文件
ActionListener listener = new MyListener();
butt.addActionListener(listener);
在我的监听器添加此
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File("path/to/file");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
不错的解决方案,但为了完整性,您将如何处理上述“其他”情况(即不支持“桌面”)? – Kingsolmn
我将补充aravindKrishna的答案,它为我工作。我希望这段代码对某人有用:
if (Desktop.isDesktopSupported()) {
try {
ClassLoader classLoader = getClass().getClassLoader();
File myFile = new File(classLoader.getResource("package/file.pdf").getFile());
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
//Control the exception
}
}
请注意,'Desktop.open()'需要'File',而应用程序分发PDF。通常会放在Jar中,并可通过“URL”访问。 ;) –