Opening a PDF file that is packaged in a JAR

孤人 提交于 2020-01-05 04:33:09

问题


I am trying to open a PDF file that is packaged into the jar file during runtime. The basic idea is that the user clicks the help option and then it displays a help file that is a PDF. Right now I have this in LineFit.class in the linefit package to try and open the help PDF:

try {
  File test = new File(LineFit.class.getClass().getResource("/linefit/helpTest.pdf").toURI());
  try {
      Desktop.getDesktop().open(test);
  } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
  } 
} catch (URISyntaxException e2) {
  // TODO Auto-generated catch block
  e2.printStackTrace();
}

It works in eclipse when I run it but if I try to export it to a runnable JAR file it does not open the PDF file and when I look into the JAR, the PDF is in the same folder as when it was in eclipse.


回答1:


new File(URI) only works for file: URIs. When a classloader finds a resource in a jar, it returns a jar URI, for example jar:file:/C:/Program%20Files/test.jar!/foo/bar.

Fundamentally, the File class is for files on the filesystem. You can't use it to represent a file within a JAR or another archive. You're going to have to copy the file out of the jar and into a regular file, then create a File referencing this new file. To read the file from the jar, you could use JarURLConnection.getInputStream with the URL you have, or you could call ClassLoader.getResourceAsStream.



来源:https://stackoverflow.com/questions/23685567/opening-a-pdf-file-that-is-packaged-in-a-jar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!