java.awt.Desktop
Recently, I discovered the java.awt.Desktop class (added in Java6) and it’s really helpful to trigger various operating system tasks such as opening a website, a PDF or even opens a file for editing in the operating system’s default editor.
In this post I’ve compiled a few ways to demonstrate the usefulness of the class and hopefully something that’ll help you to achieve something easily too.
The Desktop class is static and you can simply grab an instance with Desktop.getDesktop()
.
In the instance where your code may or may not run as expected there is a simple utility method Desktop.isSupported()
which provides some level of certainty to whether you can utilise this utility and the current point of runtime.
In addition to this, there is another method Desktop.getDesktop().isSupported(Desktop.Action.OPEN)
that provides some feedback as to whether the particular supported action is available, think Printing, Emailing etc.
Opening a PDF File
At some point in the past, to programmatically open a PDF file I’ve implemented a somewhat clumsy solution that extracted the install location of Adobe Acrobat or Adobe Reader from the Windows Registry and then called the application via Java’s shell execute ability. The Desktop class provides an alternative and very simple solution:
String fileToOpen = "G:\\Dropbox\\ClimateChange\\2014-03-09_state-of-the-climate-2014_low-res.pdf";
File file = new File(fileToOpen);
Desktop.getDesktop().open(file);
Editing a Text File
Just as easy as opening a file you can also edit a file with the operating system default file association:
String fileToEdit = "G:\\Dropbox\\notes.txt"
File file = new File(fileToEdit)
Desktop.getDesktop().edit(file)
Opening a Web Page
Launching a web page is just as easy:
String urlToOpen = "https://news.ycombinator.com";
URI addr = new URI(urlToOpen);
Desktop.getDesktop().browse(addr);
Summary
All in all these features are hardly forging new boundaries, but they’re certainly convenient and hopefully can save you some time along the way.