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
DDDOriginal
2024-12-07 00:40:15284browse

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

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

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"

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!

Statement:
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