Java Path Relative Get getRelativePath(File fromDir, File toFile)

Here you can find the source of getRelativePath(File fromDir, File toFile)

Description

get the path to a given file relative to a given directory

License

Open Source License

Parameter

Parameter Description
fromDir the directory having the file from which the link refers
toDir the directory to which a link refers

Return

the relative path

Declaration

public static String getRelativePath(File fromDir, File toFile) 

Method Source Code

//package com.java2s;
/*/*from   ww w  .  ja v  a  2s  .  co m*/
 * This file is part of the Scriba source distribution. This is free, open-source 
 * software. For full licensing information, please see the LicensingInformation file
 * at the root level of the distribution.
 *
 * Copyright (c) 2006-2007 Kobrix Software, Inc.
 */

import java.io.File;

public class Main {
    public static final char URL_SEPARATOR_CHAR = '/';

    /**
     * get the path to a given file relative to a given directory
     * 
     * @param fromDir the directory having the file from which the link refers
     * @param toDir the directory to which a link refers
     * 
     * @return the relative path
     */
    public static String getRelativePath(File fromDir, File toFile) {
        String fromStr = fromDir.getAbsolutePath();
        if (!fromStr.endsWith(File.separator)) {
            fromStr = fromStr + File.separator;
        }
        String toStr = toFile.getAbsolutePath();
        int pos = fromStr.indexOf(File.separator);
        int fromLen = fromStr.length();
        int toLen = toStr.length();
        int oldPos = pos;
        while ((pos > -1) && (pos < fromLen) && (pos < toLen)
                && (fromStr.substring(0, pos).equalsIgnoreCase(toStr.substring(0, pos)))) {
            oldPos = pos + 1;
            pos = fromStr.indexOf(File.separator, oldPos);
        }
        int samePos = oldPos;
        int level = 0;
        while (pos > -1) {
            ++level;
            oldPos = pos + 1;
            pos = fromStr.indexOf(File.separator, oldPos);
        }
        StringBuffer relPath = new StringBuffer();
        if (level > 0) {
            for (int i = 0; i < level; i++) {
                relPath.append("..");
                relPath.append(File.separator);
            }
        }
        relPath.append(toStr.substring(samePos));
        return relPath.toString().replace(File.separatorChar, URL_SEPARATOR_CHAR);
    }
}

Related

  1. getRelativePath(File file, File root)
  2. getRelativePath(File file, File srcDir)
  3. getRelativePath(File file, String xmlDirectoryPath)
  4. getRelativePath(File fileOrFolder, File baseFolder)
  5. getRelativePath(File folderContainingFile, File fileInFolder)
  6. getRelativePath(File fromFile, File toFile)
  7. getRelativePath(File fromFile, File toFile)
  8. getRelativePath(File fromFile, File toFile)
  9. getRelativePath(File fromFile, File toFile)