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

How to Construct Relative Paths from Absolute Paths in Java?

DDD
Release: 2024-12-08 04:56:10
Original
880 people have browsed it

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
Copy after login

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"
Copy after login

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!

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