从java启动pdf文件

时间:2013-06-19 10:03:57

标签: java netbeans file-io exception-handling rundll32

我正在尝试从以下代码中打开pdf文件。

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();    
    }  

print语句给出了文件的正确路径,即
目前的目录使用 System:/Users/mshariff/NetBeansProjects/javaGUIbuilding/Report.pdf
但程序出现以下错误。

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

我正在使用Mac OSX& Netbeans

1 个答案:

答案 0 :(得分:2)

您手头的解决方案只适用于Windows(rundll32是Windows命令)

相反,您应该利用Desktop API

例如......

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();
    }
}