Java Program to Get the Parts of an URL

bookmark

import java.net.URL;
public class Main
{
   //Driver method
   public static void main(String args[]) throws Exception 
   {
      //Input URL
      URL u = new URL("https://btechgeeks.com/java-programming-examples/#Java_Star_Pattern_Programs");
      //String representation of the URL
      System.out.println("URL is: " + u);
      //Get the Protocol
      System.out.println("Protocol is: " + u.getProtocol());
      //Get the File name
      System.out.println("File part is: " + u.getFile());
      //Get the Host name
      System.out.println("Host is: " + u.getHost());
      //Get the Path
      System.out.println("Path is: " + u.getPath());
      //Get the Port
      System.out.println("Port is: " + u.getPort());
      //Get the Default port
      System.out.println("Default port is: " + u.getDefaultPort());
   }
}

 


Output:

URL is: https://btechgeeks.com/java-programming-examples/#Java_Star_Pattern_Programs
Protocol is: https
File part is: /java-programming-examples/
Host is: btechgeeks.com
Path is: /java-programming-examples/
Port is: -1
Default port is: 443