1

I am trying to open a pdf file from the following code.

try {  
         String currentDir = System.getProperty("user.dir");   
         currentDir = currentDir+"/Report.pdf";  
         System.out.println("Current dir using System:" +currentDir);  
         if ((new File(currentDir)).exists()) 
             {  
         Process p = Runtime  
         .getRuntime()
     .exec("rundll32 url.dll,FileProtocolHandler " +currentDir);  
     p.waitFor();  
     }   
         else 
             {    
        System.out.println("File is not exists");   
     }  
    System.out.println("Done");   
}
    catch (Exception ex) 
        {      
    ex.printStackTrace();    
    }  

The print statement gives me the correct path of the file , i.e
Current dir using System:/Users/mshariff/NetBeansProjects/javaGUIbuilding/Report.pdf
but the program is giving the following error.

java.io.IOException: Cannot run program "rundll32": error=2, No such file or directory

I am using Mac OSX & Netbeans.

Gaurav Manral
  • 600
  • 4
  • 7
  • 24
CleanX
  • 1,158
  • 3
  • 17
  • 25
  • 1
    Have you tried using [java.awt.Desktop](http://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html)? For [examples](http://docs.oracle.com/javase/tutorial/uiswing/misc/desktop.html) – MadProgrammer Jun 19 '13 at 10:10
  • 1
    If your using MacOS, how do you expect `rundll32` to work, seen as its a Windows command...? – MadProgrammer Jun 19 '13 at 10:25

1 Answers1

3

The solution you have at hand will only work an Windows (rundll32 is a Windows command)

Instead, you should take advantage of Desktop API

For example...

public static void main(String[] args) {
    try {
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            desktop.open(new File("Your.pdf"));
        } else {
            System.out.println("Open is not supported");
        }
    } catch (IOException exp) {
        exp.printStackTrace();
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I am able to open the file with this,Thanks!!! , But I am encountering a new problem now. When I run the Program the file opens only for the first time. When I close the file , and update and click open again. It doesn't open again although the file is updated. – CleanX Jun 19 '13 at 14:29
  • I figured it out , Actually I had declared String currentDir1 = System.getProperty("user.dir"); as static globally. So every time I clicked the button . report.pdf was getting added to the string. So it opened first. Then later it had the wrong address within it . – CleanX Jun 19 '13 at 17:00