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 :
- open the default web browser, pointed to a given URI.
- open the default email client, ready to compose an email. This is accomplished by passing a mailTo URI to the Desktop class. The mailTo URI lets you specify the recipients of the email, its subject, and even its content. The size of the content is limited, however (which is a bit annoying). For example, Microsoft Outlook limits you to 512 characters. A second limitation is that file attachments cannot be specified using a mailto URI.
- open a file for editing or viewing (text file, graphics file, or whatever)
- print a file with an application's print command
The Desktop class has a fairly 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.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; 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){ File file = new File(aFileName); try { fDesktop.open(file); } 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 :
Would you use this technique?
|
|