Getting URI’s Last Segment in Java
Interacting with Uniform Resource Identifiers (URIs) is a frequent task, often encountered in both web development and file organization. Additionally, a prevalent requirement involves extracting the final segment of a URL, which refers to the portion following the last / character. Let us delve into understanding how to retrieve the last path segment from a URI in Java.
1. Using URI Class to Obtain the Last Path Segment of a URI in Java
When working with URIs in Java, the URI class provides convenient methods to extract various components, including the last path segment. Here’s a Java code snippet:
package com.jcg.example;
import java.net.URI;
import java.net.URISyntaxException;
public class URILastPathSegment {
public static void main(String[] args) {
try {
// Sample URI
String urlString = "https://www.example.com/path/to/resource/file.txt";
URI uri = new URI(urlString);
// Get the path
String path = uri.getPath();
// Split the path by '/'
String[] segments = path.split("/");
// Get the last segment
String lastSegment = segments[segments.length - 1];
// Output the last path segment
System.out.println("Last Path Segment: " + lastSegment);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
1.1 Code Explanation
This Java code defines:
- We import the necessary packages:
java.net.URIfor working with URIs andjava.net.URISyntaxExceptionfor handling URI syntax exceptions. - We create a class named
URILastPathSegment. - In the
mainmethod, we define a sample URI string. - We create a new
URIobject using the provided URI string. - We retrieve the path component of the URI using the
getPath()method. - We split the path into segments using the
split()method, with ‘/’ as the delimiter. - We obtain the last segment by accessing the last element of the
segmentsarray. - Finally, we output the last path segment.
When you run the above Java code, it will produce the following output:
Last Path Segment: file.txt
2. Using Path Class to Obtain the Last Path Segment of a URI in Java
Java’s Path class, part of the java.nio.file package offers convenient methods for working with file paths and URIs. Here’s a Java code snippet:
package com.jcg.example;
import java.net.URI;
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class PathLastPathSegment {
public static void main(String[] args) {
// Sample URI
String urlString = "https://www.example.com/path/to/resource/file.txt";
URI uri = URI.create(urlString);
// Convert URI to Path
Path path = FileSystems.getDefault().getPath(uri.getPath());
// Get the file name (last path segment)
String fileName = path.getFileName().toString();
// Output the last path segment
System.out.println("Last Path Segment: " + fileName);
}
}
2.1 Code Explanation
This Java code defines:
- We import necessary packages:
java.net.URIfor URI manipulation andjava.nio.file.FileSystemsandjava.nio.file.Pathfor working with file paths. - We create a class named
PathLastPathSegment. - In the
mainmethod, we define a sample URI string. - We create a
URIobject from the provided URI string. - Using
FileSystems.getDefault().getPath(), we convert the URI to a Path object. - We obtain the last segment of the path (file name) using the
getFileName()method. - Finally, we output the last path segment.
When you run the above Java code, it will produce the following output:
Last Path Segment: file.txt
3. Using FilenameUtils Class to Obtain the Last Path Segment of a URI in Java
In Java, the FilenameUtils class from the Apache Commons IO library offers convenient methods for handling file and path operations. Here’s a Java code snippet:
package com.jcg.example;
import org.apache.commons.io.FilenameUtils;
import java.net.URI;
public class FilenameUtilsLastPathSegment {
public static void main(String[] args) {
// Sample URI
String urlString = "https://www.example.com/path/to/resource/file.txt";
URI uri = URI.create(urlString);
// Get the last path segment using FilenameUtils
String lastSegment = FilenameUtils.getName(uri.getPath());
// Output the last path segment
System.out.println("Last Path Segment: " + lastSegment);
}
}
3.1 Code Explanation
This Java code defines:
- We import the
org.apache.commons.io.FilenameUtilsclass for working with file names and paths. - We create a class named
FilenameUtilsLastPathSegment. - In the
mainmethod, we define a sample URI string. - We create a
URIobject from the provided URI string. - Using
FilenameUtils.getName(), we extract the last path segment from the URI. - Finally, we output the last path segment.
When you run the above Java code, it will produce the following output:
Last Path Segment: file.txt
4. Using Regular Expressions to Obtain the Last Path Segment of a URI in Java
Regular expressions provide a powerful tool for pattern matching and string manipulation in Java. Here’s a Java code snippet:
package com.jcg.example;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexLastPathSegment {
public static void main(String[] args) {
// Sample URI
String urlString = "https://www.example.com/path/to/resource/file.txt";
URI uri = URI.create(urlString);
// Define the regular expression pattern
Pattern pattern = Pattern.compile(".*/([^/]+)$");
// Match the pattern against the URI path
Matcher matcher = pattern.matcher(uri.getPath());
// Check if a match is found
if (matcher.find()) {
// Get the last path segment
String lastSegment = matcher.group(1);
// Output the last path segment
System.out.println("Last Path Segment: " + lastSegment);
} else {
System.out.println("No path segment found.");
}
}
}
4.1 Code Explanation
This Java code defines:
- We import the necessary packages:
java.net.URIfor URI manipulation andjava.util.regexfor regular expressions. - We create a class named
RegexLastPathSegment. - In the
mainmethod, we define a sample URI string. - We define a regular expression pattern that matches the last path segment of a URI.
- We create a
Patternobject using the compiled regular expression. - We create a
Matcherobject and match it against the URI path. - If a match is found, we extract the last path segment using
matcher.group(1). - Finally, we output the last path segment.
When you run the above Java code, it will produce the following output:
Last Path Segment: file.txt
5. Conclusion
We explored methods for extracting the last path segment of a URI in Java. The URI class offers a straightforward solution, allowing developers to parse URIs and access their components easily. Alternatively, the Path class, part of the java.nio.file package, provides advanced file and path manipulation capabilities, enabling direct retrieval of the last segment. For those leveraging the Apache Commons IO library, the FilenameUtils class presents a convenient option, streamlining path operations with its getName() method. Moreover, regular expressions offer a highly flexible approach, enabling complex pattern matching to isolate the last path segment. Each method carries its advantages, from simplicity and platform independence to enhanced functionality and customization options. By mastering these techniques, Java developers can adeptly manage URI manipulation tasks, ensuring the efficiency and reliability of their applications.

