2012-05-16 129 views
1

當我開發基於桌面的應用程序時,有一個.pdf格式的用戶手冊,在用戶單擊幫助菜單項時應該打開該手冊。如何在java中打開.pdf文件

我不知道從swing應用程序打開.pdf文件的方式,所以我如何在我的jframe或任何pdf文件查看器(如acrobat reader)中打開它。

+0

請注意,'Desktop.open()'需要'File',而應用程序分發PDF。通常會放在Jar中,並可通過「URL」訪問。 ;) –

回答

0

嘗試使用此Runtime.getRuntime().exec("cmd PDF_FILE")。這將在Acrobat Reader中打開pdf,就像雙擊該文件一樣。

1
Desktop desktop = Desktop.getDesktop(); 
File file = new File(path); 
desktop.open(file); 

將打開系統默認瀏覽器文件

4
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 
      } 
     } 
+0

不錯的解決方案,但爲了完整性,您將如何處理上述「其他」情況(即不支持「桌面」)? – Kingsolmn

0

我將補充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 
} 
}