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

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

Description

get Relative Path

License

Open Source License

Declaration

public static String getRelativePath(File home, File f) 

Method Source Code


//package com.java2s;
/*//from   w ww .  j a  va 2s  .c  o m
 * Copyright (c) Erasmus MC
 *
 * This file is part of TheMatrix.
 *
 * TheMatrix 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.
 *
 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static String getRelativePath(File home, File f) {

        return matchPathLists(getPathList(home), getPathList(f));

    }

    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;

    }

    private static List<String> getPathList(File f) {

        List<String> l = new ArrayList<String>();

        File r;

        r = f.getAbsoluteFile();

        while (r != null) {

            l.add(r.getName());

            r = r.getParentFile();

        }

        return l;

    }
}

Related

  1. getRelativePath(File fromFile, File toFile)
  2. getRelativePath(File fromFile, File toFile)
  3. getRelativePath(File fromFile, File toFile)
  4. getRelativePath(File fromFolder, File toFile)
  5. getRelativePath(File home, File f)
  6. getRelativePath(File home, File f)
  7. getRelativePath(File original, File directory)
  8. getRelativePath(File parent, File child)
  9. getRelativePath(File parent, File child)