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

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

Description

Returns the path of one File relative to another.

License

Open Source License

Parameter

Parameter Description
target the target directory
base the base directory

Return

target's path relative to the base directory

Declaration

public static String getRelativePath(File target, File base) 

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 final String SEPARATOR = "/";

    /**//from  w w  w . ja v  a 2 s.  c o m
     * Returns the path of one File relative to another.
     * <p/>
     * From http://stackoverflow.com/questions/204784
     *
     * @param target the target directory
     * @param base   the base directory
     * @return target's path relative to the base directory
     */
    public static String getRelativePath(File target, File base) {
        String[] baseComponents;
        String[] targetComponents;
        baseComponents = getFullPath(base).split(Pattern.quote(SEPARATOR));
        targetComponents = getFullPath(target).split(Pattern.quote(SEPARATOR));

        // skip common components
        int index = 0;
        for (; index < targetComponents.length && index < baseComponents.length; ++index) {
            if (!targetComponents[index].equals(baseComponents[index]))
                break;
        }

        StringBuilder result = new StringBuilder();
        if (index != baseComponents.length) {
            // backtrack to base directory
            for (int i = index; i < baseComponents.length; ++i)
                result.append("..").append(SEPARATOR);
        }
        for (; index < targetComponents.length; ++index)
            result.append(targetComponents[index]).append(SEPARATOR);
        if (!target.getPath().endsWith("/") && !target.getPath().endsWith("\\")) {
            // remove final path separator
            result.delete(result.length() - SEPARATOR.length(), result.length());
        }
        return result.toString();
    }

    public static String getFullPath(File f) {
        try {
            return f.getCanonicalPath().replace('\\', '/');
        } catch (IOException e) {
            throw new RuntimeException("Could not get canonical path of file " + f, e);
        }
    }
}

Related

  1. getRelativePath(File rootDirectory, File file)
  2. getRelativePath(File source, File destination)
  3. getRelativePath(File source, File target)
  4. getRelativePath(File src, File dst)
  5. getRelativePath(File subj, File relativeTo)
  6. getRelativePath(File target, File relativeTo)
  7. getRelativePath(File wd, File file)
  8. getRelativePath(final File base, final File child)
  9. getRelativePath(final File base, final File name)