Calling URL Browser From Java Application
Kushal Paudyal August 21st, 2010
This program teaches you how you can call the browser in your OS to open the URL that you are passing from your Java application. This program is fully compiled and tested.
package com.kushal.utilities;
/**
* @author Kushal Paudyal
* www.sanjaal.com/java
* Last Modified On: 26th August, 2008
*/
import java.lang.reflect.Method;
import javax.swing.JOptionPane;
public class OpenDefaultBrowserFromJava {
private static final String errMsg = "ERROR WHILE ATTEMPTEING TO LUNCH WEB BROWSER";
private static final String errFindingBrowser="COULD NOT FIND THE BROWSER";
public static void main(String args [])
{
String urlToOpen="http://www.sanjaal.com/java";
openURL(urlToOpen);
}
/**
* This method takes URL as a parameter and tries to
* identify Operating system and then lunches the broswer
* with the given URL
*/
public static void openURL(String url) {
String operatingSystem = System.getProperty("os.name");
try {
/*
* Check if it is windows OS
*/
if (operatingSystem.startsWith("Windows"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
/*
* If not windows OS, Check if it is a Mac OS
*/
else if (operatingSystem.startsWith("Mac OS")) {
Class fileManager = Class.forName("com.apple.eio.FileManager");
Method openURL = fileManager.getDeclaredMethod("openURL",
new Class[] { String.class });
openURL.invoke(null, new Object[] { url });
}
/*
* Or, it might be some unix or linux OS
*/
else {
/**
* There are different browsers possible.
*/
String[] browsers = { "firefox",
"netscape",
"opera",
"konqueror",
"epiphany",
"mozilla"};
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
if (Runtime.getRuntime().exec(
new String[] { "which", browsers[count] })
.waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new Exception(errFindingBrowser);
else
Runtime.getRuntime().exec(new String[] { browser, url });
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, errMsg + ":\n" + e.getMessage());
}
}
}
Sanjaal.com is owned and maintained by Sanjaal Corps, Nepal. The company offers Webhosting and Domain Registration Services, IT Solutions and Business Analysis. Sanjaal.com website features H1B Visa Information, Entertainment Portal, Link Directory Service, Free Articles, Free Open Source Tutorials on Java and J2EE Platform, Digital Photography, High Resolution Picture Gallery and Free Reliable Image Hosting Services. Future plan includes Open Source Software Development Portal, Technical Solutions and Customizable Movie and Music Arena. We would be introducing data backup, data recovery, data hosting and voip solutions. Stay free from phishing - our website does not ask for your credit card and banking information. Happy Surfing!
Originally posted 2008-08-26 19:11:38.