Launch other applications

In Swing applications, the Desktop class gives you a simple way to launch common tools found on the great majority of personal computers. With Desktop, you can: Desktop also has operations that use the system's file associations, which map file extensions to corresponding default applications. Such mapping is used to:

The Desktop class has a pleasingly simple API. Here's an example of its use. Note that when you create an email, you often need to pay attention to encoding issues (see below).

import java.awt.Desktop;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Exercise the Desktop class. */
public final class ExerDesktop {

  public static void main(String... aArgs){
    if(Desktop.isDesktopSupported()){
      ExerDesktop test = new ExerDesktop();
      test.openURLInDefaultBrowser("http://www.date4j.net");
      //hard-coded to a given file :
      test.openFile("C:\\Temp\\blah.txt");
      test.composeEmail();
    }
    else {
      log("Desktop is not supported by this host.");
    }
  }
  
  /** Open a browser. */
  void openURLInDefaultBrowser(String aUrl){
    try {
      URI uri = new URI(aUrl);
      fDesktop.browse(uri);
    }
    catch (URISyntaxException ex) {
      log("URL is malformed. Cannot open browser.");
    }
    catch (IOException ex) {
      log("Cannot open browser.");
    }
  }
  
  /**
   Open a file using the system's mapping of file extension to default application. 
  */
  void openFile(String aFileName){
    Path path = Paths.get(aFileName);
    try {
      fDesktop.open(path.toFile());
    }
    catch (IOException ex) {
      log("File not found: " + aFileName);
    }
  }
  
  /** 
   Opens the default email client with prepopulated content, but doesn't send the email.
   You should test your own email clients and character sets.
  */
  void composeEmail(){
    try {
      String url = 
        "mailTo:you@xyz.com,me@abc.com" + 
        "?subject=" + getEmailSubject() + 
        "&body=" + getEmailBody()
      ;
      URI mailTo = new URI(url);
      //log(mailTo);
      fDesktop.mail(mailTo);
    }
    catch (IOException ex) {
      log("Cannot launch mail client");
    }
    catch (URISyntaxException ex) {
      log("Bad mailTo URI: " + ex.getInput());
    }
  }
  
  // PRIVATE
  private Desktop fDesktop = Desktop.getDesktop(); 

  private static final Pattern SIMPLE_CHARS = Pattern.compile("[a-zA-Z0-9]");
 
  private static void log(Object aMessage){
    System.out.println(String.valueOf(aMessage));
  }
  
  private String getEmailSubject(){
    return encodeUnusualChars("This is test #1.");
  }
  
  private String getEmailBody(){
    StringBuilder result = new StringBuilder();
    String NL = System.getProperty("line.separator"); 
    result.append("Hello,");
    result.append(NL);
    result.append(NL);
    //exercises a range of common characters :
    result.append("Testing 1 2 3. This is a 'quote', _yes_? ($100.00!) 5*3");
    return encodeUnusualChars(result.toString());
  }
  
  /** 
   This is needed to handle special characters.
   This method hasn't been tested with non-Latin character sets.
   
   Encodes all text except characters matching [a-zA-Z0-9]. 
   All other characters are hex-encoded. The encoding is '%' plus the hex 
   representation of the character in UTF-8. 
   
   <P>See also :
   http://tools.ietf.org/html/rfc2368 - mailto
   http://tools.ietf.org/html/rfc1738 - URLs
  */
  private String encodeUnusualChars(String aText){
    StringBuilder result = new StringBuilder();
    CharacterIterator iter = new StringCharacterIterator(aText);
    for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
      char[] chars = {c};
      String character = new String(chars);
      if(isSimpleCharacter(character)){
        result.append(c);
      }
      else {
        hexEncode(character, "UTF-8", result);
      }
    }
    return result.toString();
  }
  
  private boolean isSimpleCharacter(String aCharacter){
    Matcher matcher = SIMPLE_CHARS.matcher(aCharacter);
    return matcher.matches();
  }
  
  /**
   For the given character and encoding, appends one or more hex-encoded characters.
   For double-byte characters, two hex-encoded items will be appended.
  */
  private static void hexEncode(String aCharacter, String aEncoding, StringBuilder aOut) {
    try  {
      String HEX_DIGITS = "0123456789ABCDEF"; 
      byte[] bytes = aCharacter.getBytes(aEncoding);
      for (int idx = 0; idx < bytes.length; idx++) {
        aOut.append('%');
        aOut.append(HEX_DIGITS.charAt((bytes[idx] & 0xf0) >> 4));
        aOut.append(HEX_DIGITS.charAt(bytes[idx] & 0xf));
      }
    }
    catch (UnsupportedEncodingException ex) {
      log(ex.getStackTrace());
    }
  }
} 

See Also :
Send an email
Send trouble ticket emails
Validate email addresses