Java Relative Path Get relativePath(File descendant, File root)

Here you can find the source of relativePath(File descendant, File root)

Description

Compute the relative path between two files: root descendant returned /a/b/c /a/b/c/d.txt d.txt /a/b/c /a/b/c/d/e.txt d/e.txt /a/b/c /a/b/d.txt ''

License

Apache License

Parameter

Parameter Description
descendant the descendant file
root the root folder

Return

the relative path if files match, empty string otherwise

Declaration

public static String relativePath(File descendant, File root) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    /**/* www  . j  a  v a2  s  .  co  m*/
     * Compute the relative path between two files:
     *   root             descendant            returned
     *   /a/b/c           /a/b/c/d.txt          d.txt
     *   /a/b/c           /a/b/c/d/e.txt        d/e.txt
     *   /a/b/c           /a/b/d.txt            ''
     *
     * @param descendant  the descendant file
     * @param root        the root folder
     *
     * @return the relative path if files match, empty string otherwise
     */
    public static String relativePath(File descendant, File root) {
        try {
            String rootPath = root.getCanonicalPath().replace('\\', '/');
            String descendantPath = descendant.getCanonicalPath().replace('\\', '/');
            if (descendantPath.startsWith(rootPath))
                return descendantPath.substring(rootPath.length() + 1);
            return "";
        } catch (IOException ex) {
            return "";
        }
    }
}

Related

  1. relativeFileName(final File baseDir, final File file)
  2. relativeFrom(File from, File to)
  3. relativePath(File baseDir, File child)
  4. relativePath(File baseDir, File storeFile)
  5. relativePath(File baseDir, File storeFile)
  6. relativePath(File file, String path)
  7. relativePath(File from, File to)
  8. relativePath(File home, File f)
  9. relativePath(File IncludedFile, File UpperDirectory)