If you ever wondered if there is an easy way to open a URL from your Java program in the user-default browser, with Java SE 6 there is. Unless your platform doesn't support this. The good news is that you can test if this is the case or not.
In Java SE 6 a new class has been added to the java.awt package: Desktop. This class has a public class method isDesktopSupported() which returns true if the class is supported on the current platform, and false otherwise.
If the class is supported, you can retrieve an instance using the class method getDesktop().
You can use the browse() method to display a URI in the default browser.
If this browser is not able to handle the specified URI, the application registered
for handling the URIs of the specified type is invoked. For example, the
URI news:comp.lang.perl.misc
might invoke a Usenet client.
However, before you call the browse() method make sure to check if this action is supported on the current platform by calling the isSupported() method with java.awt.Desktop.Action.BROWSE as the value of the first and only parameter.
Note that even though this method returns true, it's still possible that the platform doesn't support the URI - for example if there is no application registered for the given scheme. In this case the browse() method will throw an IOException.
Below follows a small example program that can be invoked from the command line. It attempts to open each argument as a URI in the user-default browser, or if the browser can't handle the URI, an attempt is made to pass the URI to the application registered for the URI's scheme.
import java.net.URI;
import java.awt.Desktop;
public class OpenURI {
public static void main(String [] args) {
if( !java.awt.Desktop.isDesktopSupported() ) {
System.err.println( "Desktop is not supported (fatal)" );
System.exit( 1 );
}
if ( args.length == 0 ) {
System.out.println( "Usage: OpenURI [URI [URI ... ]]" );
System.exit( 0 );
}
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
if( !desktop.isSupported( java.awt.Desktop.Action.BROWSE ) ) {
System.err.println( "Desktop doesn't support the browse action (fatal)" );
System.exit( 1 );
}
for ( String arg : args ) {
try {
java.net.URI uri = new java.net.URI( arg );
desktop.browse( uri );
}
catch ( Exception e ) {
System.err.println( e.getMessage() );
}
}
}
}
Besides the browse() method there are 5 more methods, providing support for the 4 following Desktop actions: