Java Path Relative Get getRelativePath(File base, File target)

Here you can find the source of getRelativePath(File base, File target)

Description

Returns the relative path from base to target.

License

Open Source License

Declaration

public static String getRelativePath(File base, File target) 

Method Source Code


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

import java.io.File;

public class Main {
    /**/*from   ww w.j av  a 2 s.c o m*/
     * Returns the relative path from base to target.
     * Example:
     * base =   new File("aa/bb/cc/dd/foo.ext")
     * target = new File("aa/bb/ee/bar.ext");
     * result = "../../ee/bar.ext
     */
    public static String getRelativePath(File base, File target) {
        String baseString = base.getAbsolutePath().replace('\\', '/');
        String targetString = target.getAbsolutePath().replace('\\', '/');

        String commonPrefix = findGreatestCommonPrefix(baseString, targetString);

        if (commonPrefix.length() == 0) {
            throw new IllegalArgumentException("Arguments must have common prefix");
        }

        String relativePath = targetString.substring(commonPrefix.length());
        // relativePath = "ee/bar.ext"

        if (commonPrefix.length() == baseString.length()) {
            // base is prefix for target.
            return relativePath;
        } else {
            // Convert remainder to ../ sequence, for example
            // "cc/dd/foo.ext" to "../../"
            String remainder = baseString.substring(commonPrefix.length());
            StringBuffer cdParent = new StringBuffer();
            for (char c : remainder.toCharArray()) {
                if (c == '/') {
                    cdParent.append("../");
                }
            }
            return cdParent.toString() + relativePath;
        }
    }

    private static String findGreatestCommonPrefix(String a, String b) {
        int previousSlashIndex = -1;
        int i;
        for (i = 0; i < Math.min(a.length(), b.length()) && a.charAt(i) == b.charAt(i); i++) {
            if (a.charAt(i) == '/') {
                previousSlashIndex = i;
            }
        }

        return a.substring(0, previousSlashIndex + 1);
    }
}

Related

  1. getRelativePath(File base, File file)
  2. getRelativePath(File base, File name)
  3. getRelativePath(File base, File name)
  4. getRelativePath(File base, File path)
  5. getRelativePath(File base, File path)
  6. getRelativePath(File baseDir, File file)
  7. getRelativePath(File baseDir, File file)
  8. getRelativePath(File baseDir, File file)
  9. getRelativePath(File baseDir, File file)