Open browser with URL using Java program

Objective:
How to open browser with specific URL by using Java program? irrespective of Windows, Mac, Linux or Unix OS.

Introduction:
In this article we will learn how to write a program to open a browser with URL using Java program. First we need to find which OS we are running the program. This will help to run browser specific code on different OS. Also, this program gonna work in different Operating Systems like Windows, Mac, Linux and Unix. Below line of code will help to find the current OS,

String os = System.getProperty("os.name").toLowerCase();

Then we need to run the browser specific code based on identified OS.

For Windows:

Runtime rt = Runtime.getRuntime();
rt.exec("rundll32 url.dll, FileProtocolHandler " + url);

For Mac:

Runtime rt = Runtime.getRuntime();
rt.exec("open " + url);

For Linux/Unix:

Runtime rt = Runtime.getRuntime();
String[] browsers = { "epiphany", "firefox", "mozilla", "konqueror",
                                   "netscape", "opera", "links", "lynx" };

StringBuffer cmd = new StringBuffer();
for (int i = 0; i < browsers.length; i++) {
    if(i == 0)
       cmd.append(String.format("%s \"%s\"", browsers[i], url));
    else
       cmd.append(String.format(" || %s \"%s\"", browsers[i], url)); 
}
rt.exec(new String[] { "sh", "-c", cmd.toString() });

Look at the complete program in below

package com.tester.blog;

import java.io.IOException;

public class BrowserTest {
 static Runtime rt = Runtime.getRuntime();

 public static void main(String[] args) throws IOException {
  findOSAndOpenURL("https://www.javaisocean.com");
 }
 
 public static void findOSAndOpenURL(String url) throws IOException{
  String os = System.getProperty("os.name").toLowerCase();
  System.out.println("System OS running on : "+os);
  if(os.contains("windows")) 
    browseURLInWindows(url);
  else if(os.contains("mac"))
   browseURLInMac(url);
  else if(os.contains("unix") || os.contains("linux"))
   browseURLInLinux(url);
  else
   System.out.println("Not Found Matching OS");
 }

 public static void browseURLInWindows(String url) throws IOException{
  rt.exec("rundll32 url.dll, FileProtocolHandler " + url);
 }
 
 public static void browseURLInMac(String url) throws IOException{
  rt.exec("open " + url);
 }
 
 public static void browseURLInLinux(String url) throws IOException{
  String[] browsers = { "epiphany", "firefox", "mozilla", "konqueror",
                                   "netscape", "opera", "links", "lynx" };

  StringBuffer cmd = new StringBuffer();
  for (int i = 0; i < browsers.length; i++) {
      if(i == 0)
          cmd.append(String.format("%s \"%s\"", browsers[i], url));
      else
          cmd.append(String.format(" || %s \"%s\"", browsers[i], url)); 
  }
  rt.exec(new String[] { "sh", "-c", cmd.toString() });
 }
}
Advertisement