Home >Java >javaTutorial >How Can I Construct a Relative Path from Two Absolute Paths in Java?

How Can I Construct a Relative Path from Two Absolute Paths in Java?

DDD
DDDOriginal
2024-12-07 07:20:15585browse

How Can I Construct a Relative Path from Two Absolute Paths in Java?

Relative Path Construction from Absolute Paths in Java

Consider the challenge of constructing a relative path from two absolute paths. For instance, given these absolute paths:

/var/data/stuff/xyz.dat
/var/data

The desired relative path, with the second path as its base, is:

./stuff/xyz.dat

How can this be achieved effectively in Java?

Solution Using URI

To solve this problem, consider utilizing Java's URI class. URI provides a method, relativize, which automates the process of creating a relative path based on the provided absolute paths.

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

String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();

// relative == "stuff/xyz.dat"

Solution Using Java 1.7 Path

If your Java version is 1.7 or later, you can also leverage the relativize method available in java.nio.file.Path.

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

Path basePath = Paths.get(base);
Path absPath = Paths.get(path);
Path relativePath = basePath.relativize(absPath);

// relativePath == Paths.get("stuff/xyz.dat")

The above is the detailed content of How Can I Construct 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