Is there any way to have a code that opens a PDF file in Java application in a platform independant way? I mean using a batch file in Windows could do that. Is there any other way to have a platform independent code to open PDF files on the fly?
有沒有辦法讓代碼以獨立於平台的方式在Java應用程序中打開PDF文件?我的意思是在Windows中使用批處理文件可以做到這一點。有沒有其他方法可以使用平台無關的代碼來動態打開PDF文件?
5 个解决方案
#1
73
我試試Desktop.open(文件),其中:
Launches the associated application to open the file.
啟動關聯的應用程序以打開文件。
So this code should do the trick:
所以這段代碼應該可以解決問題:
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File("/path/to/file.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
#2
2
You can use Runtime to execute and script and there are also several Java PDF viewers out there (ie Icepdf, JPedal, PDFRenderer).
您可以使用Runtime來執行和編寫腳本,還有幾個Java PDF查看器(即Icepdf,JPedal,PDFRenderer)。
#3
1
Michael Meyer's solution didn't quite work for me. Specifically, a path with spaces fails with an IllegalArgumentException rather than an IOException.
Michael Meyer的解決方案並不適合我。具體來說,帶有空格的路徑失敗,帶有IllegalArgumentException而不是IOException。
Here's what works for me:
這對我有用:
if (Desktop.isDesktopSupported()) {
try {
File theUMFile = new File(usersManualPath);
Desktop.getDesktop().open(theUMFile);
}
catch (FileNotFoundException fnf){
okDialog(msg_fnf);
theConcours.GetLogger().log(Level.SEVERE, null, fnf);
theConcours.GetLogger().info(msg_fnf);
}
catch (IllegalArgumentException fnf) {
okDialog(msg_fnf);
theConcours.GetLogger().log(Level.SEVERE, null, fnf);
theConcours.GetLogger().info(msg_fnf);
}
catch (IOException ex) {
okDialog(msg_cno);
theConcours.GetLogger().log(Level.SEVERE, null, ex);
theConcours.GetLogger().info(msg_cno);
}
}
#4
0
Use this to open pdf file using java
使用它來使用java打開pdf文件
File file = new File(filepath);
if (file.toString().endsWith(".pdf"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + file);
else {
Desktop desktop = Desktop.getDesktop();
desktop.open(file);
}
This code is used to open your pdf and other files.
此代碼用於打開您的pdf和其他文件。
#5
-3
Use this code to open a specific file:
使用此代碼打開特定文件:
String cmds[] = new String[] {"cmd", "/c", "C:\\Users\\PC\\Desktop\\EA01.pdf"};
try {
Runtime.getRuntime().exec(cmds);
}