Launch the application associated with a file extensionTag(s): IO


JDK1.6
The java.awt.Desktop class uses your host operating system's file associations to launch applications associated with specific file types.

First it's a good idea to check if the Desktop operations are supported on the running plateform.

import java.awt.*;
...

if (Desktop.isDesktopSupported()) {
    Desktop desktop = Desktop.getDesktop();
    for (Desktop.Action action : Desktop.Action.values()) {
      System.out.println("action " + action + " supported?  " 
         + desktop.isSupported(action));
        }
}
The possible actions are
  • BROWSE. launching the user-default browser to show a specified URI
  • MAIL. launching the user-default mail client with an optional mailto URI;
  • OPEN. launching a registered application to open a specified file.
  • EDIT. launching a registered application to edit a specified file.
  • PRINT. launching a registered application to print a specified file.

    then

    // application associated to a file extension
    public static void open(File document) throws IOException {
        Desktop dt = Desktop.getDesktop();
        dt.open(document);
    }
    
    public static void print(File document) throws IOException {
        Desktop dt = Desktop.getDesktop();
        dt.print(document);
    }
    
    // default browser
    public static void browse(URI document) throws IOException {
        Desktop dt = Desktop.getDesktop();
        dt.browse(document);
    }
    
    // default mail client
    //   use the mailto: protocol as the URI
    //    ex : mailto:elvis@heaven.com?SUBJECT=Love me tender&BODY=love me sweet
    public static void mail(URI document) throws IOException {
        Desktop dt = Desktop.getDesktop();
        dt.mail(document);
    }
    
    See the javadoc at http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html

    See also this HowTo and this one.


    blog comments powered by Disqus