I don't think it's very frequent, but sometimes you want to start from one path and find the relative path of another. In Java7 or later, I think that java.nio.file.Path
is often used for file operations (original path operations), but if you want to find a relative path while using __Path
Use Path :: relativize
for. __
The JavaDoc will be the following URL: https://docs.oracle.com/javase/jp/8/docs/api/java/nio/file/Path.html#relativize-java.nio.file.Path-
It is a little difficult to understand how to use the API, but specify the path for which you want to find the relative path as an argument and the path you want to use as the starting point for the receiver.
The following is a sample to find the relative path of the file / a / b / c / directory / e / file
starting from the directory / a / b / c / directory
. It is assumed that the file / a / b / c / directory / e / file
is stored in the directory / a / b / c / directory
.
package main;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
var directory = Paths.get("/a/b/c/directory");
var file = Paths.get("/a/b/c/directory/e/file");
System.out.println(directory.relativize(file)); // => e\file
}
}
Recommended Posts