Here you can find the source of getRelativePath(Path rootPath, Path path)
Parameter | Description |
---|---|
rootPath | the supposed base path from the given target path. |
path | the target path. |
Parameter | Description |
---|---|
IOException | if something goes wrong. |
public static String getRelativePath(Path rootPath, Path path) throws IOException
//package com.java2s; import java.io.IOException; import java.nio.file.*; public class Main { /**/*from w w w . java2s .c om*/ * Gets the relative path based on a root path and a target path. * * @param rootPath the supposed base path from the given target path. * @param path the target path. * @return the relative path. * @throws IOException if something goes wrong. */ public static String getRelativePath(Path rootPath, Path path) throws IOException { // return path.relativize(rootPath).toString(); String relativePath = ""; // to avoid java.nio.file.NoSuchFileException lets use the absolute path string // to check if the given paths are the same. String r = rootPath.toString().trim(); String p = path.toString().trim(); // if (!isSame(rootPath, path) && path.startsWith(rootPath)) { if (!p.equalsIgnoreCase(r) && p.startsWith(r)) { relativePath = path.subpath(rootPath.getNameCount(), path.getNameCount()).toString(); } // throw new IllegalArgumentException("The provided paths are same or the first path parameter is not parent of the second path parameter"); return relativePath; } }