Java Path Relative Get getRelativePath(final String base, final File targetFile)

Here you can find the source of getRelativePath(final String base, final File targetFile)

Description

Returns a relative path for the targetFile relative to the base directory.

License

Apache License

Parameter

Parameter Description
base base directory as returned by File.getCanonicalPath()
targetFile target file

Return

relative path of target file. Returns targetFile if there were no commonalities between the base and the target

Declaration

public static String getRelativePath(final String base, final File targetFile) 

Method Source Code


//package com.java2s;
/*//from ww w .  j  a v  a  2  s .  c o  m
 *
 * Copyright 2001-2004 The Ant-Contrib project
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import java.io.File;
import java.io.IOException;

public class Main {
    /**
     * Returns a relative path for the targetFile relative to the base
     * directory.
     *
     * @param base
     *            base directory as returned by File.getCanonicalPath()
     * @param targetFile
     *            target file
     * @return relative path of target file. Returns targetFile if there were
     *         no commonalities between the base and the target
     *
     */
    public static String getRelativePath(final String base, final File targetFile) {
        try {
            //
            //   remove trailing file separator
            //
            String canonicalBase = base;
            if (base.charAt(base.length() - 1) != File.separatorChar) {
                canonicalBase = base + File.separatorChar;
            }
            //
            //   get canonical name of target
            //
            String canonicalTarget;
            if (System.getProperty("os.name").equals("OS/400"))
                canonicalTarget = targetFile.getPath();
            else
                canonicalTarget = targetFile.getCanonicalPath();
            if (canonicalBase.startsWith(canonicalTarget + File.separatorChar)) {
                canonicalTarget = canonicalTarget + File.separator;
            }
            if (canonicalTarget.equals(canonicalBase)) {
                return ".";
            }
            //
            //  see if the prefixes are the same
            //
            if (canonicalBase.substring(0, 2).equals("\\\\")) {
                //
                //  UNC file name, if target file doesn't also start with same
                //      server name, don't go there
                int endPrefix = canonicalBase.indexOf('\\', 2);
                String prefix1 = canonicalBase.substring(0, endPrefix);
                String prefix2 = canonicalTarget.substring(0, endPrefix);
                if (!prefix1.equals(prefix2)) {
                    return canonicalTarget;
                }
            } else {
                if (canonicalBase.substring(1, 3).equals(":\\")) {
                    int endPrefix = 2;
                    String prefix1 = canonicalBase.substring(0, endPrefix);
                    String prefix2 = canonicalTarget.substring(0, endPrefix);
                    if (!prefix1.equals(prefix2)) {
                        return canonicalTarget;
                    }
                } else {
                    if (canonicalBase.charAt(0) == '/') {
                        if (canonicalTarget.charAt(0) != '/') {
                            return canonicalTarget;
                        }
                    }
                }
            }
            char separator = File.separatorChar;
            int lastCommonSeparator = -1;
            int minLength = canonicalBase.length();
            if (canonicalTarget.length() < minLength) {
                minLength = canonicalTarget.length();
            }
            //
            //  walk to the shorter of the two paths
            //      finding the last separator they have in common
            for (int i = 0; i < minLength; i++) {
                if (canonicalTarget.charAt(i) == canonicalBase.charAt(i)) {
                    if (canonicalTarget.charAt(i) == separator) {
                        lastCommonSeparator = i;
                    }
                } else {
                    break;
                }
            }
            StringBuffer relativePath = new StringBuffer(50);
            //
            //   walk from the first difference to the end of the base
            //      adding "../" for each separator encountered
            //
            for (int i = lastCommonSeparator + 1; i < canonicalBase.length(); i++) {
                if (canonicalBase.charAt(i) == separator) {
                    if (relativePath.length() > 0) {
                        relativePath.append(separator);
                    }
                    relativePath.append("..");
                }
            }
            if (canonicalTarget.length() > lastCommonSeparator + 1) {
                if (relativePath.length() > 0) {
                    relativePath.append(separator);
                }
                relativePath.append(canonicalTarget.substring(lastCommonSeparator + 1));
            }
            return relativePath.toString();
        } catch (IOException ex) {
        }
        return targetFile.toString();
    }
}

Related

  1. getRelativePath(final File file, final File folder)
  2. getRelativePath(final File from, final File to)
  3. getRelativePath(final File fromFile, final File toFile)
  4. getRelativePath(final File parentDir, final File file)
  5. getRelativePath(final File parentDirectory, final File file)
  6. getRelativePath(String base, String fullPath)
  7. getRelativePath(String base, String relative, boolean isBaseFile)
  8. getRelativePath(String baseFullPath, File file)
  9. getRelativePath(String basePath, String path)