Java URL Relative getRelativeUrl(File basePath, File targetPath)

Here you can find the source of getRelativeUrl(File basePath, File targetPath)

Description

get Relative Url

License

Open Source License

Declaration

public static String getRelativeUrl(File basePath, File targetPath) 

Method Source Code


//package com.java2s;
/*/*from   w ww  .  jav a  2 s .  c  o  m*/
 * Created 2006/07/09
 * Copyright (C) 2003-2006  Naoki Iwami (naoki@limy.org)
 *
 * This file is part of limy-portal.
 *
 * This program 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 2
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

import java.io.File;

public class Main {

    public static String getRelativeUrl(File basePath, File targetPath) {

        String baseAbsPath = basePath.getAbsolutePath();
        String targetAbsPath = targetPath.getAbsolutePath();
        return getRelativeUrl(baseAbsPath, targetAbsPath);
    }

    public static String getRelativeUrl(String orgBaseDir, String orgTargetPath) {
        String basePath = orgBaseDir.replace('\\', '/');
        String targetPath = orgTargetPath.replace('\\', '/');
        if (targetPath.startsWith(basePath + "/")) {
            return targetPath.substring(basePath.length() + 1);
        }
        StringBuilder result = new StringBuilder();

        int reverseNo = 0;
        while (basePath.length() > 0 && !targetPath.startsWith(basePath + "/")) {
            if (basePath.lastIndexOf('/') >= 0) {
                basePath = basePath.substring(0, basePath.lastIndexOf('/'));
            } else {
                basePath = "";
            }
            result.append("../");
            ++reverseNo;
        }
        if (basePath.length() == 0) {
            return result.toString() + targetPath;
        }
        return result.toString() + targetPath.substring(basePath.length() + 1);
    }
}

Related

  1. getRelativeNameOrURL(File baseDir, File file)
  2. getRelativeURI(File fromFile, File toFile)
  3. getRelativeURL(File base, File file)
  4. getRelativeURLAsStream(Class clazz, String fileName)