當我開發基於桌面的應用程序時,有一個.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」訪問。 ;) –