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"

Exception

Parameter Description
IOException if files have no common sub-directories, i.e. at best sharethe root prefix "/" or "C:\"

Return

the relative name

Declaration


public static String getRelativePath(File base, File name) throws IOException 

Method Source Code


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

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

public class Main {
    /**/*from w w  w  .  ja v  a 2s .  com*/
     * 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
     * @throws IOException
     *             if files have no common sub-directories, i.e. at best share
     *             the root prefix "/" or "C:\"
     */

    public static String getRelativePath(File base, File name) throws IOException {
        File parent = base.getParentFile();

        if (parent == null) {
            throw new IOException("No common directory");
        }

        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));
        }
    }
}

Related

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