What a great feature! I just called my default PDF reader (guess what...) and my default Java ME emulator (the WTK 2.5) from a Swing application with these few lines of code.
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
else {
// Desktop not supported handling...
}
if (desktop.isSupported(Desktop.Action.OPEN)) {
try {
desktop.open(new File(yourFilePathHere));
}
catch (Exception ex) {
// exception handling...can be a nullpointer, an IO or an IllegalArgumentException...
}
}
else {
// Open file action not supported...
}
As you can guess from the code, the Desktop API is basically the Desktop class and its own inner class Action.
Desktop can open or edit all the files associated with an application with the method calls
desktop.open(File file)and desktop.edit(File file)but it can also open web page URIs in the default browser using the method
desktop.browse(URI uri)or open your default e-mail client, already filled with receiver addresses and mail body text, with
desktop.mail() and desktop.mail(URI uri) where the URI concatenates receveiver and body text.The Action class defines the five different actions that can be performed by the Desktop class: OPEN, BROWSE, EDIT, MAIL and PRINT (yes, print!)
The only annoying side of this API is the always-check-for-support one. Since Desktop.getDesktop() can throw many different Exceptions, you better call it after you check if isDesktopSupported(). Same rule for the Actions: you always must check if the're supported. But this is a fair cost to pay in order to call you system applications easier and faster than with the old ways.
Note: the Desktop API is not a complete replacement for all the runtime.exec() usages, but it helps reducing the number of calls to a sometimes hard to handle way to interact with your host system.
0 commenti:
Post a Comment