Java Open Web Page

In this tutorial, I will be sharing the java program to open a web page in Java. The program will open the given URL in the default browser. We have covered the Windows, Linux, and macOS operating system. We will use the java.awt.Desktop class to achieve our goal for Windows OS whereas java.lang.Runtime class for macOS and Linux.

Read Also: Default value of boolean and boolean array in Java

Steps for Open Web Page Java Program:

1. We will store an URL to open i.e "https://javahungry.blogspot.com" in String object named url as shown below:
 String url = "https://javahungry.blogspot.com/";

2. Windows OS

We need to call the browse() method on java.awt.Desktop.getDesktop() and passing the above url as a URI as shown below in the code:
 Desktop.getDesktop().browse(new URI(url));

Mac OS

For Mac OS, we need to get the runtime object and then execute the following command on it:
 runtime.exec("open " + url);

Linux

For Linux also, we need to get the runtime object and then execute the following command on it:
 runtime.exec("xdg-open " + url);

Open Web Page Java Program:

 import java.net.URI;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URISyntaxException;
public class OpenWebPage {
    public static void main(String args[]) throws IOException, URISyntaxException {
        // Url of the web page to open
        String url = "https://javahungry.blogspot.com";
        // Your operating system
        String myOS = System.getProperty("os.name").toLowerCase();
        if(Desktop.isDesktopSupported()) {
            // Windows
            Desktop.getDesktop().browse(new URI(url));
            System.out.println("Web page opened in your default browser");
        }
        else {
            Runtime runtime = Runtime.getRuntime();
            //Mac OS
            if(myOS.contains("mac")) {
                runtime.exec("open " + url);
            }
            // Linux
            else {
                runtime.exec("xdg-open " + url);
            }
        }
    }
}


Output:



java open web page


That's all for today, please mention in the comments in case you have any questions related to Java open web page.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry