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:
That's all for today, please mention in the comments in case you have any questions related to Java open web page.
 


0 Commentaires