从Java应用程序动态打开PDF文件 2 周,3 日 Questions & Answers 103763 有没有办法让代码以独立于平台的方式在Java应用程序中打开PDF文件?我的意思是在Windows中使用批处理文件可以做到这一点。有没有其他方法可以让平台无关的代码在运行中打开PDF文件
# 1 楼答案 我想试试^{},它: Launches the associated application to open the 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 } }
# 2 楼答案 使用以下代码打开特定文件: String cmds[] = new String[] {"cmd", "/c", "C:\\Users\\PC\\Desktop\\EA01.pdf"}; try { Runtime.getRuntime().exec(cmds); }
# 4 楼答案 迈克尔·迈耶的解决方案对我不太管用。具体来说,带有空格的路径失败时会出现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); } }
# 5 楼答案 第三方应用程序无法访问应用程序中的src dir,以防应用程序在jar存档中组装。您应该将文件与src分开放置 当然,java会找到图标,因为它是JavaAPI。您可以通过以下方法访问src文件夹中的任何资源: URL url = getClass().getResource("/path/in/src"); File file = new File(url.toURI()); 我目前正在使用以下软件: if (Desktop.isDesktopSupported()) { try { URL url = getClass().getResource("/pdf/XXXX.pdf"); File myFile = new File(url.toURI()); Desktop.getDesktop().open(myFile); } catch (IOException | URISyntaxException ex) { // no application registered for PDFs } }
# 6 楼答案 使用此选项可以使用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和其他文件
# 1 楼答案
我想试试^{} ,它:
所以这段代码应该做到:
# 2 楼答案
使用以下代码打开特定文件:
# 3 楼答案
您可以使用Runtime来执行和编写脚本,还有几个Java PDF查看器(即Icepdf、JPedal、PDFRenderer)
# 4 楼答案
迈克尔·迈耶的解决方案对我不太管用。具体来说,带有空格的路径失败时会出现IllegalArgumentException,而不是IOException
以下是对我有效的方法:
# 5 楼答案
第三方应用程序无法访问应用程序中的src dir,以防应用程序在jar存档中组装。您应该将文件与src分开放置
当然,java会找到图标,因为它是JavaAPI。您可以通过以下方法访问src文件夹中的任何资源:
我目前正在使用以下软件:
# 6 楼答案
使用此选项可以使用java打开pdf文件
此代码用于打开pdf和其他文件