Header Ads Widget

Responsive Advertisement

How to open the default web browser using java

Opening the default web browser in Java can be done using the java.awt.Desktop class, which provides methods for launching associated applications based on the operating system's file type and URI associations.

Here’s a simple example demonstrating how to open a URL in the default web browser:

Example Code

Java

package com.demo;



import java.awt.Desktop;

import java.net.URI;

import java.util.LinkedList;

import java.util.List;

import java.util.Random;



public class OpenWebBrowser {

 

 private static String[] urlArray = {

   "/2016/11/how-to-convert-xml-to-object-and-object.html",

   "/2016/04/how-to-include-google-map-in-your.html",

   "/2016/04/clone-under-standing.html",

   "/2016/04/custom-binary-tree-printer.html",

   "/2016/11/public-key-encryption-and-private-key.html"};



 private static List<String> createUrl() {

  int size = urlArray.length;

  List<String> url=new LinkedList<String>();

        for (int i=0; i<size; i++)

        {

         String s="https://www.javatherapy.in"+urlArray[i];

         url.add(s);

        }

        return url;

 }



 /**

  * @param args

  */

 public static void main(String[] args) {

  try {

     Desktop desktop = java.awt.Desktop.getDesktop();

     List<String> urlString = createUrl();

     Random rand = new Random();

       while (true) {

           int choice = rand.nextInt(urlString.size());

           URI oURL = new URI(urlString.get(choice));

     desktop.browse(oURL);

           Thread.sleep(20000);

       }

   } catch (Exception e) {

     e.printStackTrace();

   }



 }

}

 

 

Explanation

  1. Check if Desktop API is Supported:

Java

if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {

 

    • The Desktop.isDesktopSupported() method checks if the Desktop API is supported on the current platform.
    • The Desktop.getDesktop().isSupported(Desktop.Action.BROWSE) method checks if the BROWSE action is supported.
  1. Create a URI Object:

Java

URI uri = new URI("http://www.example.com");

 

    • Creates a URI object with the specified URL.
  1. Open the Default Web Browser:

Java

Desktop.getDesktop().browse(uri);

 

    • Uses the browse method to open the default web browser and navigate to the specified URI.
  1. Exception Handling:

java

} catch (Exception e) {

    e.printStackTrace();

}

 

    • Catches and prints any exceptions that might occur, such as URISyntaxException or IOException.

Running the Code

  1. Save the Code: Save the code to a file named OpenWebBrowser.java.
  2. Compile the Code: Open a terminal or command prompt and navigate to the directory containing the file. Compile the code using:

javac OpenWebBrowser.java

  1. Run the Code: Execute the compiled class using:

java OpenWebBrowser

 

Notes

  • This code will open the specified URL (http://www.example.com) in the default web browser.
  • Ensure that the java.awt.Desktop class is available in your Java environment. It has been available since Java SE 6.
  • If running in a restricted environment (like a server without a graphical interface), the Desktop API might not be supported.

This approach provides a straightforward way to open URLs in the default web browser from a Java application.

 

 

Approach 2:

 

If the Desktop API is not available, you can use runtime commands to open the web browser.

java

import java.io.IOException;

 

public class OpenWebBrowser {

    public static void main(String[] args) {

        String url = "http://www.example.com";

        try {

            // Detect the operating system

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

 

            // Linux

            if (os.contains("linux")) {

                // Try to open the URL with common browsers

                String[] browsers = { "xdg-open", "google-chrome", "firefox", "mozilla", "netscape" };

                boolean success = false;

                for (String browser : browsers) {

                    if (Runtime.getRuntime().exec(new String[] { "which", browser }).waitFor() == 0) {

                        Runtime.getRuntime().exec(new String[] { browser, url });

                        success = true;

                        break;

                    }

                }

                if (!success) {

                    throw new UnsupportedOperationException("No supported web browser found.");

                }

            } else {

                throw new UnsupportedOperationException("Unsupported operating system.");

            }

        } catch (IOException | InterruptedException | UnsupportedOperationException e) {

            e.printStackTrace();

        }

    }

}

 

Explanation

  1. Approach 2: Using Runtime Commands:
    • Detecting the Operating System:

Java

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

 

      • Detects the operating system name.
    • Executing Browser Commands:

Java

String[] browsers = { "xdg-open", "google-chrome", "firefox", "mozilla", "netscape" };

boolean success = false;

for (String browser : browsers) {

    if (Runtime.getRuntime().exec(new String[] { "which", browser }).waitFor() == 0) {

        Runtime.getRuntime().exec(new String[] { browser, url });

        success = true;

        break;

    }

}

 

      • Tries to find and execute common browser commands using Runtime.getRuntime().exec().
      • The which command checks if the browser is installed, and if it is, the URL is opened with that browser.

Running the Code

  1. Save the Code: Save the code to a file named OpenWebBrowser.java.
  2. Compile the Code: Open a terminal and navigate to the directory containing the file. Compile the code using:

Sh

javac OpenWebBrowser.java

  1. Run the Code: Execute the compiled class using:

Sh

java OpenWebBrowser

Notes

  • Ensure that you have one of the common browsers installed on your Linux system (xdg-open, google-chrome, firefox, etc.).
  • The xdg-open command is a desktop-independent tool for opening URLs and files. It should be available on most modern Linux distributions.
  • For more robust error handling, you may want to provide additional checks and fallback mechanisms as needed.

 



open the default web browser
open the default web browser







Post a Comment

0 Comments