Java open url in default system browser

open a url in system default browser - work for all  : windows, mac, linux operating systems

Full working JAVA source code example
import java.io.IOException;
public class StartBrowserUtil {
    private StartBrowserUtil() {
    }
    public static void openURL(String s) {
        String s1 = System.getProperty("os.name").toLowerCase();
        Runtime runtime = Runtime.getRuntime();
        try {
            if (s1.indexOf("windows") >= 0)
                runtime.exec(new String[] { "rundll32", "url.dll,FileProtocolHandler", s });
            else if (s1.indexOf("mac") >= 0) {
                Runtime.getRuntime().exec(new String[] { "open", s });
            } else {
                // linux
                String as[] = { "firefox", "mozilla-firefox", "mozilla", "konqueror", "netscape", "opera" };
                boolean isSuccess = false;
                int i = 0;
                do {
                    if (i >= as.length)
                        break;
                    try {
                        runtime.exec(new String[] { as[i], s });
                        isSuccess = true;
                        break;
                    } catch (Exception exception) {
                        i++;
                    }
                } while (true);
                if (!isSuccess) {
                    System.out.println("Please open a browser and go to " + s);
                }
            }
        } catch (IOException ioexception) {
            System.out.println("Failed to start a browser to open the URL " + s);
            ioexception.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println(System.getProperty("os.name"));
        openURL("http://ganeshtiwaridotcomdotnp.blogspot.com/");
    }
}




No comments :

Post a Comment

Your Comment and Question will help to make this blog better...