Android Path Relative Get convertToRelativePath(String absolutePath, String relativeTo)

Here you can find the source of convertToRelativePath(String absolutePath, String relativeTo)

Description

taken from http://mrpmorris.blogspot.com/2007/05/convert-absolute-path-to-relative-path.html

License

Apache License

Declaration

public static String convertToRelativePath(String absolutePath,
        String relativeTo) 

Method Source Code

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

public class Main {
    /**// w w w .  j a  va 2s  .  c om
     * taken from
     * http://mrpmorris.blogspot.com/2007/05/convert-absolute-path-to-relative-path.html
     */
    public static String convertToRelativePath(String absolutePath,
            String relativeTo) {
        StringBuilder relativePath = null;

        absolutePath = absolutePath.replaceAll("\\\\", "/");
        relativeTo = relativeTo.replaceAll("\\\\", "/");

        if (absolutePath.equals(relativeTo) == true) {

        } else {
            String[] absoluteDirectories = absolutePath.split("/");
            String[] relativeDirectories = relativeTo.split("/");

            //Get the shortest of the two paths
            int length = absoluteDirectories.length < relativeDirectories.length ? absoluteDirectories.length
                    : relativeDirectories.length;

            //Use to determine where in the loop we exited
            int lastCommonRoot = -1;
            int index;

            //Find common root
            for (index = 0; index < length; index++) {
                if (absoluteDirectories[index]
                        .equals(relativeDirectories[index])) {
                    lastCommonRoot = index;
                } else {
                    break;
                    //If we didn't find a common prefix then throw
                }
            }
            if (lastCommonRoot != -1) {
                //Build up the relative path
                relativePath = new StringBuilder();
                //Add on the ..
                for (index = lastCommonRoot + 1; index < absoluteDirectories.length; index++) {
                    if (absoluteDirectories[index].length() > 0) {
                        relativePath.append("../");
                    }
                }
                for (index = lastCommonRoot + 1; index < relativeDirectories.length - 1; index++) {
                    relativePath.append(relativeDirectories[index] + "/");
                }
                relativePath
                        .append(relativeDirectories[relativeDirectories.length - 1]);
            }
        }
        return relativePath == null ? null : relativePath.toString();
    }
}

Related

  1. getPathRelativeTo(File fileChild, File fileRoot)
  2. getRelativeFileName(File file, File basedir)
  3. getRelativePath(File parent, File file)
  4. getWindowsRelativePath(String basedir, String path)