打开打包在JAR中的PDF文件
我正在尝试打开在运行时打包到jar文件中的PDF文件。基本思想是用户单击帮助选项,然后显示PDF格式的帮助文件。现在我在linefit包中的LineFit.class中尝试打开帮助PDF:
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();
}
当我运行它时它在eclipse中工作但是如果我尝试将它导出到一个可运行的JAR文件,它不会打开PDF文件,当我查看JAR时,PDF与eclipse中的文件夹在同一文件夹中。
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.
新文件(URI)
仅适用于文件:
URI。当类加载器在jar中找到资源时,它返回一个 jar
URI,例如 jar:file:/ C:/ Program%20Files / test .jar!/ foo / bar
。
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
.
从根本上说,文件
类适用于文件系统上的文件。您不能使用它来表示JAR或其他存档中的文件。您将不得不将文件从jar中复制到常规文件中,然后创建引用此新文件的文件
。要从jar中读取文件,可以使用 JarURLConnection。带有您的URL的getInputStream ,或者您可以调用 ClassLoader.getResourceAsStream 。
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.