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

Apache License

Declaration

public static String getRelativePath(File home, File f) 

Method Source Code

//package com.java2s;
/*/*  w  w  w . j  a  v  a 2 s. co  m*/
 * Copyright 2005,2006 WSO2, Inc. http://www.wso2.org
 *
 * 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.List;

public class Main {
    public static String getRelativePath(File home, File f) {
        List<String> homelist;
        List<String> filelist;
        String s;

        homelist = getPathList(home);
        filelist = getPathList(f);
        s = matchPathLists(homelist, filelist);

        return s;
    }

    private static List<String> getPathList(File f) {
        List<String> l = new ArrayList<String>();
        File r;
        try {
            r = f.getCanonicalFile();
            while (r != null) {
                l.add(r.getName());
                r = r.getParentFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
            l = null;
        }
        return l;
    }

    private static String matchPathLists(List<String> r, List<String> f) {
        int i;
        int j;
        StringBuffer sb = new StringBuffer();
        i = r.size() - 1;
        j = f.size() - 1;

        while ((i >= 0) && (j >= 0) && (r.get(i).equals(f.get(j)))) {
            i--;
            j--;
        }

        for (; i >= 0; i--) {
            sb.append("..").append(File.separator);
        }

        for (; j >= 1; j--) {
            sb.append(f.get(j)).append(File.separator);
        }

        sb.append(f.get(j));
        return sb.toString();
    }
}

Related

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