Core Java

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.URI for working with URIs and java.net.URISyntaxException for handling URI syntax exceptions.
  • We create a class named URILastPathSegment.
  • In the main method, we define a sample URI string.
  • We create a new URI object 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 segments array.
  • 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.URI for URI manipulation and java.nio.file.FileSystems and java.nio.file.Path for working with file paths.
  • We create a class named PathLastPathSegment.
  • In the main method, we define a sample URI string.
  • We create a URI object 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.FilenameUtils class for working with file names and paths.
  • We create a class named FilenameUtilsLastPathSegment.
  • In the main method, we define a sample URI string.
  • We create a URI object 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.URI for URI manipulation and java.util.regex for regular expressions.
  • We create a class named RegexLastPathSegment.
  • In the main method, we define a sample URI string.
  • We define a regular expression pattern that matches the last path segment of a URI.
  • We create a Pattern object using the compiled regular expression.
  • We create a Matcher object 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.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button