我如何在java中打开.pdf文件
在我开发基于桌面的应用程序时,有一个.pdf格式的用户手册,应该在用户点击帮助菜单项时打开。
我不知道从swing应用程序打开.pdf文件的方法,所以如何在我的jframe
或任何pdf文件查看器(如acrobat reader)中打开它。
ActionListener listener = new MyListener(); butt.addActionListener(listener);
在My Listener中添加此内容
if (Desktop.isDesktopSupported()) { try { File myFile = new File( "path/to/file"); Desktop.getDesktop().open(myFile); } catch (IOException ex) { // no application registered for PDFs } }
Desktop desktop = Desktop.getDesktop(); File file = new File(path); desktop.open(file);
在默认系统查看器中打开文件
尝试使用此Runtime.getRuntime().exec("cmd PDF_FILE")
。 这将在Acrobat Reader中打开pdf,就像双击该文件一样。
我将补充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 } }