Java Path Relative nio getRelativePath(Path rootPath, Path path)

Here you can find the source of getRelativePath(Path rootPath, Path path)

Description

Gets the relative path based on a root path and a target path.

License

Open Source License

Parameter

Parameter Description
rootPath the supposed base path from the given target path.
path the target path.

Exception

Parameter Description
IOException if something goes wrong.

Return

the relative path.

Declaration

public static String getRelativePath(Path rootPath, Path path) throws IOException 

Method Source Code


//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;
    }
}

Related

  1. getRelativePath(File baseFile, File file, String resultIfImpossible)
  2. getRelativePath(File basePath, File path)
  3. getRelativePath(File root, File f)
  4. getRelativePath(final File file, final File baseDir)
  5. getRelativePath(Path file, Path baseDir)
  6. getRelativePath(String file, String directory)
  7. getRelativePath(String fullPath, String homeFolderPath)
  8. getRelativePath(String relativePathFile)
  9. getSourceFileRelativePath(Class declaringClass)