Java Relative Path Get relativePath(File home, File f)

Here you can find the source of relativePath(File home, File f)

Description

get relative path of File 'f' with respect to 'home' directory example : home = /a/b/c f = /a/d/e/x.txt s = getRelativePath(home,f) = ../../d/e/x.txt

License

Open Source License

Parameter

Parameter Description
home base path, should be a directory, not a file, or it doesn't make sense
f file to generate path for

Return

path from home to f as a string

Declaration

public static String relativePath(File home, File f) 

Method Source Code

//package com.java2s;
/**//from   w ww .jav a2  s. c  o  m
 *  Copyright 2008 Marvin Herman Froeder
 *  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;
import java.util.ArrayList;
import java.util.Arrays;

import java.util.List;

public class Main {
    /**
     * get relative path of File 'f' with respect to 'home' directory example : home = /a/b/c f = /a/d/e/x.txt s =
     * getRelativePath(home,f) = ../../d/e/x.txt
     * 
     * @param home base path, should be a directory, not a file, or it doesn't make sense
     * @param f file to generate path for
     * @return path from home to f as a string
     */
    public static String relativePath(File home, File f) {
        List<String> homelist = pathList(home);
        List<String> filelist = pathList(f);
        return matchPathLists(homelist, filelist).replace('\\', '/');
    }

    /**
     * break a path down into individual elements and add to a list. example : if a path is /a/b/c/d.txt, the breakdown
     * will be [d.txt,c,b,a]
     * 
     * @param f input file
     * @return a List collection with the individual elements of the path in reverse order
     */
    private static List<String> pathList(File f) {
        List<String> l = new ArrayList<String>();
        File r = file(f);
        while (r != null) {
            l.add(r.getName());
            r = r.getParentFile();
        }
        return l;
    }

    /**
     * figure out a string representing the relative path of 'f' with respect to 'r'
     * 
     * @param r home path
     * @param f path of file
     */
    private static String matchPathLists(List<String> r, List<String> f) {
        int i;
        int j;
        String s;
        // start at the beginning of the lists
        // iterate while both lists are equal
        s = "";
        i = r.size() - 1;
        j = f.size() - 1;

        // first eliminate common root
        while ((i >= 0) && (j >= 0) && (r.get(i).equals(f.get(j)))) {
            i--;
            j--;
        }

        // for each remaining level in the home path, add a ..
        for (; i >= 0; i--) {
            s += ".." + File.separator;
        }

        // for each level in the file path, add the path
        for (; j >= 1; j--) {
            s += f.get(j) + File.separator;
        }

        // file name
        s += f.get(j);
        return s;
    }

    public static File file(File file) {
        if (file == null) {
            return null;
        }

        try {
            return file.getCanonicalFile();
        } catch (IOException e) {
            return file.getAbsoluteFile();
        }
    }

    public static File file(String path) {
        if (path == null) {
            return null;
        }

        return file(new File(path));
    }

    public static File file(String path, File basedir) {
        if (path == null) {
            return null;
        }

        File file = new File(path);
        if (!file.isAbsolute()) {
            file = new File(basedir, path);
        }

        return file(file);
    }

    public static File file(String path, File... basedirs) {
        if (path == null) {
            return null;
        }

        return file(path, Arrays.asList(basedirs));
    }

    public static File file(String path, List<File> basedirs) {
        if (path == null) {
            return null;
        }

        File file = new File(path);

        if (file.isAbsolute()) {
            return file;
        }

        for (File basedir : basedirs) {
            file = file(path, basedir);
            if (file.exists()) {
                return file;
            }
        }

        return null;
    }

    public static File file(String path, String basedir) {
        return file(path, file(basedir));
    }
}

Related

  1. relativePath(File baseDir, File storeFile)
  2. relativePath(File baseDir, File storeFile)
  3. relativePath(File descendant, File root)
  4. relativePath(File file, String path)
  5. relativePath(File from, File to)
  6. relativePath(File IncludedFile, File UpperDirectory)
  7. relativePath(File parent, File child)
  8. relativePath(File parent, File child)
  9. relativePath(File path, File relativeTo)