开发者

Accessing a PDF in Jar

I'm crea开发者_如何学Goting a Java application using Netbeans. From the 'Help' Menu item, I'm required to open a PDF file. When I run the application via Netbeans, the document opens, but on opening via the jar file, it isn't opening. Is there anything that can be done?

m_aboutItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
           Runtime rt = Runtime.getRuntime();
                URL link2=getClass().getResource("/newpkg/Documentation.pdf");
                String link=link2.toString();
                link=link.substring(6);
                System.out.println(link);
                System.out.println(link2);
                String link3="E:/new/build/classes/newpkg/Documentation.pdf";
                try {
                Process proc = rt.exec("rundll32.exe url.dll,FileProtocolHandler " + link3);
            } catch (IOException ex) {
                Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    });

The two outputs are as follows:

E:/new/build/classes/newpkg/Documentation.pdf
file:/E:/new/build/classes/newpkg/Documentation.pdf

Consider the above code snippet. On printing 'link',we can see that it is exactly same as the hard coded 'link3'. On using the hard coded 'link3' , the PDF file gets opened from jar application. But when we use link, though it is exactly same as 'link3', the PDF doesn't open.


This is most likely related to the incorrect PDF resource loading. In the IDE you have the PDF file either as part of the project structure or with a directly specified relative path. When a packaged application is running it does not see the resource.

EDIT: Your code reveals the problem as I have described. The following method could be used to properly identify resource path.

public static URL getURL(final String pathAndFileName) {
    return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}

Pls refer to this question, which might provide additional information.


Try out this:

m_aboutItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        URL link2=Menubar1.class.getResource("/newpkg/Documentation.pdf");
            String link=link2.toString();
            link=link.substring(6);
            System.out.println(link); 
        File file=new File(link);
        System.out.println(file);
            try {
                desktop.open(file);
            } catch (IOException ex) {
                Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜