Java Path Relative Get getRelativePath(File file, File baseDir)

Here you can find the source of getRelativePath(File file, File baseDir)

Description

get Relative Path

License

Apache License

Declaration

public static String getRelativePath(File file, File baseDir) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;

public class Main {
    public static String getRelativePath(File file, File baseDir) {
        if (isFileInDirRecursive(file, baseDir)) {
            return baseDir.toURI().relativize(file.toURI()).getPath();
        } else {//from ww  w  .  j  a v a 2 s . c  om
            return getRelativePathRecursive(file, baseDir, "");
        }

    }

    protected static boolean isFileInDirRecursive(File file, File dir) {
        if (file.getParentFile() != null) {
            return file.getParentFile().equals(dir) || isFileInDirRecursive(file.getParentFile(), dir);
        }
        return false;
    }

    private static String getRelativePathRecursive(File file, File baseDir, String prefix) {
        if (isFileInDirRecursive(file, baseDir)) {
            return prefix + baseDir.toURI().relativize(file.toURI()).getPath();
        } else if (baseDir.getParentFile() != null) {
            return prefix + getRelativePathRecursive(file, baseDir.getParentFile(), "../");
        } else {
            return file.toURI().toString();
        }

    }
}

Related

  1. getRelativePath(File currentDir, File target)
  2. getRelativePath(File dir, File child)
  3. getRelativePath(File dir, File file)
  4. getRelativePath(File f, File base)
  5. getRelativePath(File file)
  6. getRelativePath(File file, File basedir)
  7. getRelativePath(File file, File baseDirectory)
  8. getRelativePath(File file, File directory)
  9. getRelativePath(File file, File folder)