Home > Java > javaTutorial > How to Get Relative Paths from Absolute URLs in Java?

How to Get Relative Paths from Absolute URLs in Java?

Linda Hamilton
Release: 2024-12-02 14:46:11
Original
441 people have browsed it

How to Get Relative Paths from Absolute URLs in Java?

Getting Relative Paths from Absolute URLs in Java

When working with paths in Java, it's often necessary to convert absolute paths into relative paths with respect to a specified base path. This can be achieved using the relativize() method provided by the java.net.URI class.

Consider the example paths:

/var/data/stuff/xyz.dat
/var/data
Copy after login

To create a relative path using the latter path as its base, you can do the following:

String path = "/var/data/stuff/xyz.dat";
String base = "/var/data";
String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
Copy after login

This code converts the absolute paths to URIs, performs the relativization, and extracts the resulting path. The output will be:

stuff/xyz.dat
Copy after login

Please note that for file paths specifically, Java 1.7 introduced the relativize() method in the java.nio.file.Path class. You can utilize this method for a more efficient solution if you are working with file paths.

The above is the detailed content of How to Get Relative Paths from Absolute URLs in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template