Search code examples
javanetbeans-7

How to Open pdf files with different paths in Java


I have a PDF file and I want to open it with my java Application. PDF file open when I run the that program with Netbeans. But when I run that program from .Jar file , That PDF file didn't open.

    try {
            String p1[] = getClass().getResource("/Scholars_Management_System_Help.pdf").toString().split("file:/");
            String helppath = p1[1].replace("%20", " ");
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + helppath);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex, "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
        }

Solution

  • I think getClass().getResource("/Scholars_Management_System_Help.pdf") locates a file called Scholars_Management_System_Help.pdf in your project root directory and when you create the jar file this file is probably not included in the jar, and that's why this is not working. You should probably run the jar from a command line inorder for you to see if there is any exception thrown. That way you could be sure of the cause of the problem.

    Again instead of running the application (pdf reader) with Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + helppath); you should instead use Desktop.getDesktop().open(file_name); which makes it more portable.