410
|
Chapter 11, Native Integration and Packaging
#79 Launch External Programs on Windows
HACK
Open a URL
You can open a web browser the same way as a text file because Windows
associates all URLs, specifically ones that begin with http, with a default web
browser. If you call
start
on a URL then the browser will open, as seen in
Example 11-2.
You can also use the browser support to open up a new email message.
Since
mailto: is a URL protocol, usually mapped to the user’s default email
program, if you open up a
mailto: URL, Windows will open a new message
ready to send (see Example 11-3).
The previous code will open up a new email message addressed to
author@mybook.com. The return address will be filled in automatically with
the user’s own address. You can remove the address (author@mybook.com)
to open a new blank email.
By default,
cmd.exe will open a requested file using the standard viewer for
that file’s type. For example,
cmd.exe /c start music.mp3 will open the song
file using the default program, possibly the Windows Media Player or
iTunes. If you would rather open the file with a particular program that you
specify, then you can simply add the program name before the file.
Example 11-2. Opening a URL in the default web browser on Windows
import java.io.IOException;
public class ExecTest {
public static void main(String[] args) throws IOException {
String cmd = "cmd.exe /c start ";
String file = "http://www.google.com";
Runtime.getRuntime( ).exec(cmd + file);
}
}
Example 11-3. Using start to open an email application
import java.io.IOException;
public class ExecTest {
public static void main(String[] args) throws IOException {
String cmd = "cmd.exe /c start ";
String file = "mailto:author@mybook.com";
Runtime.getRuntime( ).exec(cmd + file);
}
}

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.