有没有办法有一个代码在 Java 应用程序中以平台无关的方式打开 PDF 文件?我的意思是在 Windows 中使用批处理文件可以做到这一点。
我会尝试Desktop.open(File)
,其中:
启动关联的应用程序以打开文件。
所以这个代码应该做的伎俩:
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File("/path/to/file.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
您可以使用运行时执行和脚本,也有几个 Java PDF 查看器(即 Icepdf,JPedal,PDFRenderer)。

Michael Meyer 的解决方案对我来说并不是很有效。具体来说,一个带有空格的路径失败的是 IllegalArgumentException,而不是 IOException。
这是我的作品:
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);
}
}

使用它使用 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);
}
此代码用于打开您的 pdf 和其他文件。
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(64条)