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

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

Description

get Relative Path

License

Open Source License

Parameter

Parameter Description
f a parameter
base a parameter

Exception

Parameter Description
IllegalArgumentException if f is not a sub path of base

Return

the path of f, relative to base. e.g. "/a/b/c.txt" relative to "/a" is "b/c.txt" This method uses absolute paths.

Declaration

public static String getRelativePath(File f, File base) throws IllegalArgumentException 

Method Source Code

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

import java.io.File;

public class Main {
    /**//from  w  w w .ja  v  a  2s . com
     *
     * @param f
     * @param base
     * @return the path of f, relative to base. e.g. "/a/b/c.txt" relative to
     *         "/a" is "b/c.txt" This method uses absolute paths.
     * @throws IllegalArgumentException
     *             if f is not a sub path of base
     * @testedby {@link FileUtilsTest#testGetRelativePath()}
     */
    public static String getRelativePath(File f, File base) throws IllegalArgumentException {

        String fp = f.getAbsolutePath();
        String bp = base.getAbsolutePath();
        if (!fp.startsWith(bp)) {
            if (f.equals(base))
                return ""; // Is this what we want?
            throw new IllegalArgumentException(f + "=" + fp + " is not a sub-file of " + base + "=" + bp);
        }
        String rp = fp.substring(bp.length());
        if (rp.isEmpty()) {
            return rp; // f = base
        }
        char ec = rp.charAt(0); // TODO a bit more efficient
        if (ec == '\\' || ec == '/') {
            rp = rp.substring(1);
        }
        return rp;

    }
}

Related

  1. getRelativePath(File baseFolder, File subject)
  2. getRelativePath(File child, File directory)
  3. getRelativePath(File currentDir, File target)
  4. getRelativePath(File dir, File child)
  5. getRelativePath(File dir, File file)
  6. getRelativePath(File file)
  7. getRelativePath(File file, File basedir)
  8. getRelativePath(File file, File baseDir)
  9. getRelativePath(File file, File baseDirectory)