How to launch the default (native) application for

2019-01-11 15:24发布

问题:

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?

回答1:

What you want is java.awt.Desktop:

Desktop.getDesktop().open( file );


回答2:

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.



回答3:

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+).