7

I am displaying a list of files; i.e. xls, doc, pdf, odt etc., in my Java application (Eclipse RCP). When the user clicks on the file, I want to launch the appropriate (according to what the OS thinks) native application, just like it happens in Windows Explorer or the Finder.

And while I am here: It would be nice to also display the same icons that Finder or Explorer use for the different file types.

Is there a library or Eclipse plugin for this?

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 1
    This appears to be a duplicate of this question: http://stackoverflow.com/questions/325299/cross-platform-way-to-open-a-file-using-java-1-5 – Ry4an Brase Feb 18 '09 at 08:33
  • 1
    Not really, notice the Java 1.5 restriction there: "I know that Java 1.6 introduced the Desktop API, but I need a solution for Java 1.5." – Jonik Jun 11 '09 at 13:13

3 Answers3

14

What you want is java.awt.Desktop:

Desktop.getDesktop().open( file );
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Joseph Gordon
  • 2,356
  • 2
  • 23
  • 27
  • 1
    Desktop does not work well on Windows: `java.io.IOException: Failed to open file:/C:/Documents%20and%20Settings/Administrator/Desktop/test.pdf. Error message: Application not found at sun.awt.windows.WDesktopPeer.ShellExecute(Unknown Source) ~[na:1.6.0_26]` – Eero Sep 22 '11 at 12:12
  • 3
    Eero, the function is working as designed: http://download.oracle.com/javase/6/docs/api/java/awt/Desktop.html#open%28java.io.File%29 open will throw an IOException "if the specified file has no associated application or the associated application fails to be launched". You might think about prompting for an application to use if an IOException is thrown. – Joseph Gordon Sep 22 '11 at 16:17
6

I have found an API in Eclipse's SWT now that seems to do the trick: org.eclipse.swt.program.Program "provides access to facilities for discovering operating system specific aspects of external program launching."

It has methods to find the program for a given file extension, get the program's icon, and even launch the program.

Thilo
  • 257,207
  • 101
  • 511
  • 656
2

Sounds like you're after the Java Activation Framework ("JAF"). This API lets you determine what files are and what actions you can do on them. Or alternatively the Java Desktop Integration Component ("JDIC"). JDIC allows you to create and no doubt query file associations.

Both projects seem to be in a semi-abandoned state howeer (sigh). But that's par for the course for Sun these days. Only other thing I know of is some Windows specific third party library that's based on JNI called Winpack. It does a bunch of other things too.

You can get the associated icon using the FileSystemView class (Java 1.4+).

cletus
  • 616,129
  • 168
  • 910
  • 942
  • Hmm, Desktop.open() seems the simplest way. If one can use Java 6, are there some advantages to using one of these libs instead? – Jonik Jun 11 '09 at 17:57