开发者

How to load a PDF from a .jar File?

I have made a Swing application and will include a file, help.pdf in the .jar file. When the user selects Help->User Guide from a JMenuItem, it should load the file in the d开发者_JAVA百科efault PDF viewer on the system.

I have the code to load the PDF,

private void openHelp() {
    try {
        java.net.URL helpFile = getClass().getClassLoader().getResource("help.pdf");
        File pdfFile = new File(helpFile.getPath());
        if (pdfFile.exists()) {

            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().open(pdfFile);
            } else {
                System.out.println("Awt Desktop is not supported!");
            }

        } else {
            System.out.println("File does not exist!");
        }

        System.out.println("Done");

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

This works in the eclipse IDE, however, when I pack it into a jar for other people it no longer works.

How do I fix this problem?


The problem is that a File cannot name a component of a JAR file. What you need to do is to copy the resource from the JAR file into a temporary file in the filesystem, and open using the File for the temporary file.


File names in a .jar file are case sensitive. In your text you write Help.pdf but in the code you use help.pdf. The upper/lowercase in the Java code must match the case of the file, even if you are using a system where the filesystem is not case sensitive.

Try

getResource("Help.pdf");

instead (assuming the filename in your posting text is correct)


I think you have to retrieve the location of the jar, open it and load the pdf file from within your application. The .jar file is just a zipped archive, which can be read with java easily...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜