I'm trying to use Desktop
class to open a local HTML file on Windows. But it works only for some specific JREs, and not with some other JREs.
Here is my code:
try {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.OPEN)) {
desktop.open(new File("test.html"));
} else {
throw new Exception("OPEN action not supported");
}
} else {
throw new Exception("Desktop not supported");
}
} catch (Exception e) {
e.printStackTrace();
}
When it doesn't work, no Exception is thrown, and no text is printed in STDERR.
It works with:
It does not work with:
All tests were performed on the same Win7 64 bits box.
EDIT : Same issue when trying to open a "txt" or "pdf" file
Thank you.
This problem has been around for a while now and has been documented with a few solutions at this blog.
I've resorted to using the code below and it has been reliable on every Windows machine I've used regardless of JRE. I'm sorry but I don't know all of the JREs I've tested with.
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path);
As "Stijn de Witt" said in the comments of "haventchecked"'s answer, the solution based on Runtime.getRuntime()
doesn't work with UNC paths, and with paths containing consecutive spaces. Here is the solution that also works with these special paths:
new ProcessBuilder("rundll32", "url.dll,FileProtocolHandler", path).start();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With