Open PDF file on the fly from a Java application

I'd try Desktop.open(File), which:

Launches the associated application to open the file.

So this code should do the trick:

if (Desktop.isDesktopSupported()) {
    try {
        File myFile = new File("/path/to/file.pdf");
        Desktop.getDesktop().open(myFile);
    } catch (IOException ex) {
        // no application registered for PDFs
    }
}

You can use Runtime to execute and script and there are also several Java PDF viewers out there (ie Icepdf, JPedal, PDFRenderer).


Michael Meyer's solution didn't quite work for me. Specifically, a path with spaces fails with an IllegalArgumentException rather than an IOException.

Here's what works for me:

    if (Desktop.isDesktopSupported()) {
try {
File theUMFile = new File(usersManualPath);
 Desktop.getDesktop().open(theUMFile);
}
catch (FileNotFoundException fnf){
okDialog(msg_fnf);
theConcours.GetLogger().log(Level.SEVERE, null, fnf);
theConcours.GetLogger().info(msg_fnf);
}
catch (IllegalArgumentException fnf) {
 okDialog(msg_fnf);
            theConcours.GetLogger().log(Level.SEVERE, null, fnf);
            theConcours.GetLogger().info(msg_fnf);
        }
        catch (IOException ex) {
            okDialog(msg_cno);
            theConcours.GetLogger().log(Level.SEVERE, null, ex);
            theConcours.GetLogger().info(msg_cno);
        }
    } 

Use this to open pdf file using java

File file = new File(filepath);
    if (file.toString().endsWith(".pdf")) 
        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + file);
    else {
        Desktop desktop = Desktop.getDesktop();
        desktop.open(file);
}

This code is used to open your pdf and other files.