Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Desktop.open() silently fails on some JREs

Tags:

java

desktop

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:

  • JRE 1.6.0_14 (32 bits)
  • JRE 1.7.0_05 (32 bits)
  • JRE 1.7.0_45 (64 bits)
  • JRE 1.7.0_51 (64 bits)

It does not work with:

  • JRE 1.6.0_26 (64 bits)
  • JRE 1.6.0_37 (64 bits)
  • JRE 1.7.0_02 (64 bits)
  • JRE 1.7.0_21 (64 bits) EDIT : But works on CentOS

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.

like image 950
xav Avatar asked Mar 15 '14 01:03

xav


2 Answers

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);
like image 163
haventchecked Avatar answered Nov 01 '22 08:11

haventchecked


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();
like image 1
xav Avatar answered Nov 01 '22 08:11

xav