Java URL and URI classes
Java URL and URI classes
In Java, both URL and URI are classes used to work with web addresses. While they sound similar and are often used interchangeably in casual conversation, they have distinct purposes and capabilities in programming. Understanding the difference helps you choose the right tool for handling web resources in your Java applications.
Java URL Class
The URL (Uniform Resource Locator) class in Java represents a specific address that points to a resource on the web, like a webpage, image, or file. It not only identifies the resource but also tells you how to access it (e.g., using HTTP, FTP, etc.).
Here’s a simple example:
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com/index.html");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Path: " + url.getPath());
}
}
This code creates a URL object and prints its protocol (https), host (www.example.com), and path (/index.html).
Java URI Class
The URI (Uniform Resource Identifier) class is more general. It identifies a resource but doesn’t necessarily tell you how to retrieve it. A URI can be a URL (which locates a resource) or a URN (Uniform Resource Name, which names a resource uniquely but doesn’t specify location).
Here’s a simple example:
import java.net.URI; public class Main {
public static void main(String[] args) throws Exception {
URI uri = new URI("https://www.example.com/index.html");
System.out.println("Scheme: " + uri.getScheme());
System.out.println("Host: " + uri.getHost());
System.out.println("Path: " + uri.getPath());
}
}
This code creates a URI object and prints similar components. However, unlike URL, URI doesn’t support directly opening a connection to the resource.
URL vs URI
Some of the differences between URL and URI are as follows:
| URL Class | URI Class | |
|---|---|---|
| Full Form | Uniform Resource Locator | Uniform Resource Identifier |
| Purpose | Specifies both the location of a resource and how to access it | Identifies a resource (may or may not specify how to access it) |
| Access Resource | Can open a connection to the resource (e.g., via openConnection()) |
Cannot open a connection; purely for identification |
| Scope | A subset of URI | A superset that includes both URLs and URNs |
| Example | https://www.example.com/page.html |
https://www.example.com/page.html or urn:isbn:0451450523 |