Understanding basics java.awt.Desktop

UPDATED: 19 June 2013
I was finding some good topic to write an article. So looking all around my projects. I used java.awt.Desktop class in my program. Lets discuss all about the Desktop class of java.

What is java.awt.Desktop?
          java.awt.Desktop class designed to interact with system programs. It executes the system command to handle the operation of file and sometime URL(s). So now lets take a look at the methods of Desktop class. All methods throws IOException so use try-catch.

Desktop.getDesktop().browse(URI uri)
This function is used to open URL Uniform (or universal) Resource Locator. This will open the URL in system's default web browser client.
Desktop.getDesktop().browse(URI.create("http://www.javaquery.com"));

Desktop.getDesktop().edit(File file)
It'll open file specified in parameter with system related editor. Say your file is .txt, .docx, etc... Be careful with this because if there ain't any editor related to that file type it'll throws error  java.io.IOException: Failed to edit file:/c:/1.pdf. Error message: Unspecified error. I'm trying to edit .pdf file which is not supported by my system.
Desktop.getDesktop().edit(new File("c:\\1.txt"));

Desktop.getDesktop().isSupported(Action action)
This method designed to check that system user has enough privileges to do operation. System admin can set  file open, edit, print, browse and mail permission of other users. It'll return true and false based on permission.
Desktop.getDesktop().isSupported(Desktop.Action.OPEN);
Desktop.getDesktop().isSupported(Desktop.Action.EDIT);
Desktop.getDesktop().isSupported(Desktop.Action.PRINT);
Desktop.getDesktop().isSupported(Desktop.Action.BROWSE);
Desktop.getDesktop().isSupported(Desktop.Action.MAIL);

Desktop.getDesktop().mail()
It'll open the default mail client program of system.

Desktop.getDesktop().mail(URI uri)
Helps to set email, subject, message, cc and bcc on system default mail client. Predefined subject of mail and To so user don't need to remember your mail id or support mail id.
// To set space use "%20"
Desktop.getDesktop().mail(URI.create("mailto:vkijust4u@javaquery.com?subject=Hello%20World&body=This%20is%20sample%20mail&cc=example@gmail.com&bcc=example@yahoo.com"));

Desktop.getDesktop().open(File file)
Open the specified file in system's default program.
Desktop.getDesktop().open(new File("c:\\1.pdf"));

Desktop.getDesktop().print(File file)
Print the specified file in system's default printer.
Desktop.getDesktop().print(new File("c:\\1.pdf"));

Desktop.isDesktopSupported()
Tests whether this class is supported on the current platform. If it's supported, use Desktop.getDesktop() to retrieve an instance.

0 comments :