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

How to Construct Relative Paths from Absolute Paths in Java?

DDD
DDDOriginal
2024-12-08 04:56:10932browse

How to Construct Relative Paths from Absolute Paths in Java?

Constructing Relative Paths from Absolute Paths in Java

When working with absolute paths in Java, there may be instances where you need to create a relative path based on another absolute path. This article demonstrates how to achieve this using the URI class and its relativize method.

Consider the following two absolute paths:

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

To create a relative path that uses the second path as its base, follow these steps:

  1. Convert both absolute paths to URIs using the File class and the toURI method.
  2. Call the relativize method on the URI representing the base path and pass in the URI representing the absolute path.
  3. Retrieve the path component from the resulting URI to obtain the relative path.

Here is an example code snippet:

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"

This code will produce a relative path of "stuff/xyz.dat", which is the desired result.

It's worth noting that for file paths, Java 1.7 introduced the Path#relativize method, which can also be used for this purpose.

The above is the detailed content of How to Construct Relative Paths from 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