What is the URL.getPath() method in Java?

The getPath() method of the URL class in Java can be used to get the path part of the specified URLUniform Resource Locator.

The image below shows the different parts of a URL.

Parts of the url

The URL class is present in the java.net package.

Syntax

The syntax of the getPath() method is shown below.

public String getPath()

Parameters

The getPath() method doesn’t take any parameters.

Return value

The return type of this method is a string. If the URL doesn’t have a path, then an empty string is returned.

Code

The code below shows how to use the getPath() method in Java.

import java.net.URL;
class GetPathExample {
public static void main( String args[] ) {
try {
URL url= new URL("https:// www.educative.io/user/profile/view");
//Get Path
String path=url.getPath();
System.out.println("The URL is : "+url);
System.out.println("\nThe Path of the URL is : "+ path);
} catch (Exception e) {
System.out.println(e);
}
}
}

Explanation

In the code above:

  • Line 6 creates a URL object.
URL url= new URL("https:// www.educative.io/user/profile/view");
  • In line 8, the getPath() method gets the path of the URL object.
String path = url.getPath();
  • Finally, the URL and its path are printed in lines 9 and 10.

Free Resources