Java Examples - Parts of URL


Problem Description:

How to get the parts of an URL?


Following example shows how to get the parts of an URL with the help of url.getProtocol() ,url.getFile() method etc. of net.URL class.


public class Main {
   public static void main(String[] args) 
   throws Exception {
      URL url = new URL(args[0]);
      System.out.println("URL is " + url.toString());
      System.out.println("protocol is " 
      + url.getProtocol());
      System.out.println("file name is " + url.getFile());
      System.out.println("host is " + url.getHost());
      System.out.println("path is " + url.getPath());
      System.out.println("port is " + url.getPort());
      System.out.println("default port is " 
      + url.getDefaultPort());


The above code sample will produce the following result.

URL is
protocol is TCP/IP
file name is java_program.txt
host is
path is 
port is 2
default port is 1