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.
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments