Java Path Relative Get getRelativePath(String targetPath, String basePath, String pathSeparator)

Here you can find the source of getRelativePath(String targetPath, String basePath, String pathSeparator)

Description

get Relative Path

License

Open Source License

Declaration

public static String getRelativePath(String targetPath, String basePath, String pathSeparator) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;

import java.util.regex.Pattern;

public class Main {
    public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {
        String[] base = basePath.split(Pattern.quote(pathSeparator));
        String[] target = targetPath.split(Pattern.quote(pathSeparator));

        StringBuilder common = new StringBuilder();

        int commonIndex = 0;
        while (commonIndex < target.length && commonIndex < base.length
                && target[commonIndex].equals(base[commonIndex])) {
            common.append(target[commonIndex]).append(pathSeparator);
            commonIndex++;// ww w  .  j  ava 2s  . c  o m
        }

        if (commonIndex == 0) {
            return null;
        }

        if (target.length == commonIndex && base.length == target.length) {
            return "";
        }

        boolean baseIsFile = true;

        File baseResource = new File(basePath);

        if (baseResource.exists()) {
            baseIsFile = baseResource.isFile();

        } else if (basePath.endsWith(pathSeparator)) {
            baseIsFile = false;
        }

        StringBuilder relative = new StringBuilder();

        if (base.length != commonIndex) {
            int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

            for (int i = 0; i < numDirsUp; i++) {
                relative.append("..").append(pathSeparator);
            }
        }
        relative.append(targetPath.substring(common.length()));
        return relative.toString();
    }
}

Related

  1. getRelativePath(String path, String base)
  2. getRelativePath(String root, String path)
  3. getRelativePath(String rootpath, String path)
  4. getRelativePath(String source, String target)
  5. getRelativePath(String target, String base)
  6. getRelativePath(String targetPath, String basePath, String pathSeparator)
  7. getRelativePathOfZipEntry(final File fileToZip, final File base)
  8. getRelativePathRecursive(File file, File baseDir, String prefix)
  9. getRelativePathToBase(File path, File basePath)