Here you can find the source of getRelativePath(File base, File target)
public static String getRelativePath(File base, File target)
//package com.java2s; //License from project: Open Source License import java.io.File; public class Main { /**/*from ww w.j av a 2 s.c o m*/ * Returns the relative path from base to target. * Example: * base = new File("aa/bb/cc/dd/foo.ext") * target = new File("aa/bb/ee/bar.ext"); * result = "../../ee/bar.ext */ public static String getRelativePath(File base, File target) { String baseString = base.getAbsolutePath().replace('\\', '/'); String targetString = target.getAbsolutePath().replace('\\', '/'); String commonPrefix = findGreatestCommonPrefix(baseString, targetString); if (commonPrefix.length() == 0) { throw new IllegalArgumentException("Arguments must have common prefix"); } String relativePath = targetString.substring(commonPrefix.length()); // relativePath = "ee/bar.ext" if (commonPrefix.length() == baseString.length()) { // base is prefix for target. return relativePath; } else { // Convert remainder to ../ sequence, for example // "cc/dd/foo.ext" to "../../" String remainder = baseString.substring(commonPrefix.length()); StringBuffer cdParent = new StringBuffer(); for (char c : remainder.toCharArray()) { if (c == '/') { cdParent.append("../"); } } return cdParent.toString() + relativePath; } } private static String findGreatestCommonPrefix(String a, String b) { int previousSlashIndex = -1; int i; for (i = 0; i < Math.min(a.length(), b.length()) && a.charAt(i) == b.charAt(i); i++) { if (a.charAt(i) == '/') { previousSlashIndex = i; } } return a.substring(0, previousSlashIndex + 1); } }