Home > Java > javaTutorial > How to Generate a Relative Path from Two Absolute Paths in Java?

How to Generate a Relative Path from Two Absolute Paths in Java?

DDD
Release: 2024-12-07 00:40:15
Original
283 people have browsed it

How to Generate a Relative Path from Two Absolute Paths in Java?

Creating Relative Paths from Two Absolute Paths

Given two absolute paths, such as:

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

how can we generate a relative path that starts from the second path? For instance, the desired output for the paths above is:

./stuff/xyz.dat
Copy after login

Solution using URI

One approach leverages the URI class, which provides a relativize method to handle such conversions:

String path = "/var/data/stuff/xyz.dat";
String base = "/var/data";

// Convert the paths to URIs
URI pathURI = new File(path).toURI();
URI baseURI = new File(base).toURI();

// Obtain the relative URI
URI relativeURI = pathURI.relativize(baseURI);

// Extract the relative path
String relativePath = relativeURI.getPath();
// relativePath == "stuff/xyz.dat"
Copy after login

Note: For file paths specifically, Java 1.7 and later offers the relativize method on the java.nio.file.Path interface, as suggested by @Jirka Meluzin.

The above is the detailed content of How to Generate a Relative Path from Two Absolute Paths 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template