Issue
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
.
Solution
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();
}
}
Answered By - MadProgrammer