Launching files from Java

(I try again, with considerably less love than last time)

Opening files in their "natural" application was something I knew had to be done sooner or later for aperture/gnowsis/nepomuk, but I put it off for as long as possible because I had a horrible feeling that to get it to work on all platforms it would be long and messy and maybe involve nasty C code.

Imagine my surprise when in a few hours today I got it working for files, directories and web links, and this on both windows, macosx and linux (kde/gnome). All without leaving the world of Java. The code is so short I will paste it here (beautifully formatted by code2html!)

private void windowsopen(URI uri) throws IOException {
      new String [] { "rundll32", "url.dll,FileProtocolHandler",uri.toString() });
private void linuxopen(URI uri) throws IOException {
   // TODO: I don't know how reliable this is. 
   // It's set correctly for kde/gnome on my machine 
   if (System.getenv("DESKTOP_SESSION").toLowerCase().contains("kde")) {	
      Runtime.getRuntime().exec(new String [] { "kfmclient","exec",uri.toString()} );
   } else {
      //Default to gnome as it complains less if it's not running.
      Runtime.getRuntime().exec(new String [] { "gnome-open",uri.toString()} );

private void macopen(URI url) throws IOException {
   try {
      Class macopener = Class.forName("");
      Method m = macopener.getMethod("openURL",new Class[] {String.class});
      m.invoke(null,new Object[] {url.toString()});
   } catch (Exception e) {
      throw new IOException("Could not open URI: "+url+" - "+e);

This is for opening http links, but the file code is almost identical, KDE and Windows doesn't like file:// URIs so I convert them to filenames first, and launching things in Windows is done by executing "cmd /c blah" instead (Thanks Michael Sintek!).

Still damn easy. It's not very well tested yet – but it works on my three instances of each OS! If anyone feels like testing it the code is in the aperture cvs repos, and (although it's only just committed so it'll take a while for the sourceforge cvs mirrors to catch up)

Post a comment.