How to launch the default (native) application for a given file from Java?
Asked Answered
C

3

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?

Cutout answered 18/2, 2009 at 6:54 Comment(2)
This appears to be a duplicate of this question: #325799Jamestown
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."Marathi
M
14

What you want is java.awt.Desktop:

Desktop.getDesktop().open( file );
Multiplication answered 11/6, 2009 at 12:27 Comment(2)
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]Polymerism
Eero, the function is working as designed: download.oracle.com/javase/6/docs/api/java/awt/… 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.Multiplication
C
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.

Cutout answered 18/2, 2009 at 7:22 Comment(0)
C
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+).

Catchings answered 18/2, 2009 at 7:1 Comment(1)
Hmm, Desktop.open() seems the simplest way. If one can use Java 6, are there some advantages to using one of these libs instead?Marathi

© 2022 - 2024 — McMap. All rights reserved.