Here you can find the source of getRelativePath(File fromDir, File toFile)
Parameter | Description |
---|---|
fromDir | the directory having the file from which the link refers |
toDir | the directory to which a link refers |
public static String getRelativePath(File fromDir, File toFile)
//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); } }