Wednesday, September 5, 2007

Launch Web Browser through Java

Some Times Java applications need to present the user with an online resource such as a help tutorial or an interactive web site. web browsers such as Netscape or Internet Explorer have additional advanced capabilities such as supporting HTML scripting languages and various multimedia formats. This tutorial describes how to launch the user's default browser from your Java application.


import java.lang.reflect.Method;

public class BrowserControl{
* Method to Open the Broser with Given URL
* @param url
public static void openUrl(String url){
String os = System.getProperty("");
Runtime runtime=Runtime.getRuntime();
// Block for Windows Platform
if (os.startsWith("Windows")){
String cmd = "rundll32 url.dll,FileProtocolHandler "+ url;
Process p = runtime.exec(cmd);
//Block for Mac OS
else if(os.startsWith("Mac OS")){
Class fileMgr = Class.forName("");
Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class});
openURL.invoke(null, new Object[] {url});
//Block for UNIX Platform
else {
String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
String browser = null;
for (int count = 0; count < style="color: rgb(153, 0, 0);">length && browser == null; count++)
if (runtime.exec(new String[] {"which", browsers[count]}).waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new Exception("Could not find web browser");
runtime.exec(new String[] {browser, url});
}catch(Exception x){
System.err.println("Exception occurd while invoking Browser!");

Test the Code:

public static void main(String[] args){


Josh said...

Great post.

You may want to change the following line:

I made a slight modification:
(right after the BLOCK for UNIX platform)

for (int count = 0; count < browsers.length && browser == null; count++)



梦中林 said...

When the Wow Gold wolf finally found the Buy Wow Goldhole in the chimney he crawled wow gold cheap down and KERSPLASH right into that kettle of water and that was cheap wow gold the end of his troubles with the big bad wolf.
The next day the cheapest wow gold little pig invited his mother over . She said "You see it is just as mygamegoldI told you. The way to get along in the world is to do world of warcraft gold things as well as you can." Fortunately for that little pig, he buy cheap wow gold learned that lesson. And he just lived happily ever after! wow gold .

Henry Wells said...

Well said 梦中林, well said