1. Introduction
1.导言
Working with Uniform Resource Identifiers (URIs) is a common operation that is mostly used in web development and file management.
使用统一资源标识符(URIs)是一种常见操作,主要用于网络开发和文件管理。
Besides, one of the most common needs is to get the last path segment out of a URL (the last segment is the last segment after the last ‘/’ character).
此外,最常见的需求之一是获取 URL 的最后一个路径段(最后一个路径段是指最后一个”/”字符之后的最后一个路径段)。
In this tutorial, we’ll investigate different ways to obtain the last segment of a URL.
在本教程中,我们将研究获取 URL 最后一段的不同方法。
2. Using URI Class
2.使用 URI 类
The java.net.URI class enables an object-oriented approach for URI parsing and manipulation. To make it easier, let’s take an example:
java.net.URI 类支持面向对象的 URI 解析和操作方法。为了便于理解,让我们举一个例子:
@Test
public void givenURL_whenUsingURIClass_thenGetLastPathSegment() throws URISyntaxException {
URI uri = new URI("https://www.example.com/path/to/resource");
String path = uri.getPath();
String[] segments = path.split("/");
String lastSegment = segments[segments.length - 1];
assertEquals("resource", lastSegment);
}
The given method initializes a URI with a sample URL. Subsequently, the URI’s path is extracted using the getPath() method. The path is then split into segments based on the forward-slash (“/”) delimiter. The last path segment is then determined by accessing the last element of the segment array.
给定方法使用示例 URL 初始化 URI 。随后,使用 getPath() 方法提取 URI 的路径。然后根据正斜线(”/”)分隔符将路径分割成若干段。然后通过访问段数组的最后一个元素来确定最后一个路径段。
Finally, the test asserts that the last path segment matches the expected value, affirming that the functionality correctly extracts the intended resource from the URL.
最后,测试确认最后一个路径段与预期值相匹配,从而确认该功能从 URL 中正确提取了目标资源。
3. Using Path Class
3.使用 Path 类
In Java 7, the java.nio.file.Path class provides a platform-independent representation for files and paths. Providing an effective way to extract the last segment of URI. Here’s an example:
在 Java 7 中, java.nio.file.Path 类为文件和路径提供了与平台无关的表示方法。提供提取 URI 最后一段的有效方法。下面是一个示例:
@Test
public void givenURL_whenUsingPathClass_thenGetLastPathSegment() {
String exampleURI = "https://www.example.com/path/to/resource";
try {
URI uri = new URI(exampleURI);
String pathString = uri.getPath();
Path path = Paths.get(pathString);
Path lastSegment = path.getName(path.getNameCount() - 1);
assertEquals("resource", lastSegment.toString());
} catch (Exception e) {
fail("Exception occurred: " + e.getMessage());
}
}
As in the previous section, we first initialize a URI and use the getPath() method. Subsequently, we create a Path object named path from the obtained pathString. The last segment is determined using the getName() method with an index calculation. The last path segment is then converted to a string for comparison.
与上一节一样,我们首先初始化一个 URI,并使用 getPath() 方法。随后,我们根据获得的 pathString 创建一个名为 path 的 Path 对象。我们使用 getName() 方法和索引计算来确定最后一段路径。然后将最后一个路径段转换为字符串,以便进行比较。
4. Using FilenameUtils Class
4.使用 FilenameUtils 类
Apache Commons IO library has a FilenameUtils class that is available as a utility class for common file and path tasks. Let’s take an example:
Apache Commons IO 库中有一个 FilenameUtils 类,该类可作为实用程序类用于常见的文件和路径任务。让我们举个例子:
@Test
public void givenURL_whenUsingFilenameUtilsClass_thenGetLastPathSegment() throws URISyntaxException {
String exampleURI = "https://www.example.com/path/to/resource";
URI uri = new URI(exampleURI);
String path = uri.getPath();
String lastSegment = FilenameUtils.getName(path);
assertEquals("resource", lastSegment);
}
After extracting the path using the getPath() method, we utilize the FilenameUtils class to obtain the last path segment using the getName() method, which takes the path as a parameter.
使用 getPath() 方法提取 path 之后,我们利用 FilenameUtils 类,使用 getName() 方法(该方法将 path 作为参数)获取最后一个路径段。
5. Using Regular Expressions
5.使用正则表达式
In extracting the last path segment from a URL, regex provides an elegant solution for flexible and precise pattern definitions. Here’s an example:
在提取 URL 的最后一个路径段时,regex 为灵活而精确的模式定义提供了一个优雅的解决方案。下面是一个示例:
@Test
public void givenURL_whenUsingRegularExpression_thenGetLastPathSegment() throws URISyntaxException {
URI uri = new URI("https://www.example.com/path/to/resource");
String path = uri.getPath();
Pattern pattern = Pattern.compile(".*/(.+)");
Matcher matcher = pattern.matcher(path);
if (!matcher.find()) {
fail("Regex pattern didn't match.");
}
String lastSegment = matcher.group(1);
assertEquals("resource", lastSegment);
}
Here, we define a regular expression pattern “/(.+)” to capture the last segment of the URL path precisely. Leveraging the Pattern and Matcher classes, we compile and apply the regex pattern to the path string using the compile() and matcher() methods.
在此,我们定义了一个正则表达式模式”/(.+)“,以精确捕捉 URL 路径的最后一段。利用 Pattern 和 Matcher 类,我们使用 compile() 和 matcher() 方法将 regex 模式编译并应用到 path 字符串。
Moreover, a conditional check further validates the success of the regex pattern application using the find() method. Upon successful matching, the last path segment is extracted using the group(1) method from the Matcher object.
此外,条件检查使用 find() 方法进一步验证 regex 模式应用是否成功。匹配成功后,将使用 Matcher 对象中的 group(1) 方法提取最后一个路径段。
6. Conclusion
6.结论
In conclusion, this tutorial explored multiple Java methods, including the URI class, Path class, FilenameUtils, and regular expressions, providing diverse approaches to extract the last path segment from a URL effectively.
总之,本教程探讨了多种 Java 方法,包括 URI 类、Path 类、FilenameUtils 和正则表达式,提供了从 URL 中有效提取最后路径段的多种方法。
As usual, the accompanying source code can be found over on GitHub.
与往常一样,您可以在 GitHub 上找到随附的源代码。