How to open input URL in system default browser in windows in java

URL is the URL you want to display in your default web browser. For example, connect http://www.site.com/report.html to this input to display the HTML file report.html on the web server www.site.com in the browser. Our problem is to write a java program to open the input URL in the default browser of the Windows system. To open any URL, we use different java predefined files to operate our desktop.

  1. java.awt.Desktop We use the java.awt.Desktop class because with java.awt.Desktop we can interact with various functions on our desktop. For example, starting the user's default browser, starting the user's default email client, and more.
  2. java.net.URIjava.net.URI is used to Represent User Resource Identifier reference.

Algorithm:

  • Firstly, we create an Object of our defined class that we import by java.awt.Desktop.
  • During the creation of an object, we use getDesktop() method that returns the Desktop instance of the present desktop context. On some platforms, the Desktop API might not be supported, therein case, we use isDesktopSupported() method to work out if the present desktop is supported.

 

 Desktop desk=Desktop.getDesktop();
  • Then we use browse() method where we enter our URL that we want to open on our desktop by new URI().
  desk.browse(new URI("http://xyz.com"));

 

// Java Program to Open Input URL in
// System Default Browser in Windows

import java.awt.Desktop;
import java.io.*;
import java.net.URI;

class GFG {
	public static void main(String[] args)
			throws Exception
	{
		Desktop desk = Desktop.getDesktop();
		
		// now we enter our URL that we want to open in our
		// default browser
		desk.browse(new URI("http://xyz.com"));
	}
}

Output

(Our URL "http://xyz.com" will open in our desktop default browser)

 

Submit Your Programming Assignment Details