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

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

Description

Computes the path for a file relative to a given base, or fails if the only shared directory is the root and the absolute form is better.

License

Open Source License

Parameter

Parameter Description
base File that is the base for the result
name File to be "relativized"

Return

the relative name

Declaration


public static String getRelativePath(File base, File name) 

Method Source Code

//package com.java2s;
/** This file is part of Approach Avoidance Task.
 *
 * Approach Avoidance Task is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version./*from   ww  w . java  2 s .  co m*/
 *
 * Approach Avoidance Task is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Approach Avoidance Task.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

import java.io.File;

public class Main {
    /**
     * Computes the path for a file relative to a given base, or fails if the only shared
     * directory is the root and the absolute form is better.
     *
     * @param base File that is the base for the result
     * @param name File to be "relativized"
     * @return the relative name
     */

    public static String getRelativePath(File base, File name) {
        if (base != null && name != null) {
            File parent = base.getParentFile();
            if (name.getName().length() > 0) {
                try {
                    if (parent == null) {
                        return name.getAbsolutePath();
                    }
                    String bpath = base.getCanonicalPath();
                    String fpath = name.getCanonicalPath();

                    if (fpath.startsWith(bpath)) {
                        return fpath.substring(bpath.length() + 1);
                    } else {
                        return (".." + File.separator + getRelativePath(parent, name));
                    }
                } catch (Exception e) {
                    return name.getAbsolutePath();
                }
            }
        }
        return "";
    }
}

Related

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