Here you can find the source of getRelativePath(String targetPath, String basePath, String pathSeparator)
public static String getRelativePath(String targetPath, String basePath, String pathSeparator)
//package com.java2s; //License from project: Open Source License import java.io.*; import java.util.regex.Pattern; public class Main { public static String getRelativePath(String targetPath, String basePath, String pathSeparator) { String[] base = basePath.split(Pattern.quote(pathSeparator)); String[] target = targetPath.split(Pattern.quote(pathSeparator)); StringBuilder common = new StringBuilder(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].equals(base[commonIndex])) { common.append(target[commonIndex]).append(pathSeparator); commonIndex++;// ww w . j ava 2s . c o m } if (commonIndex == 0) { return null; } if (target.length == commonIndex && base.length == target.length) { return ""; } boolean baseIsFile = true; File baseResource = new File(basePath); if (baseResource.exists()) { baseIsFile = baseResource.isFile(); } else if (basePath.endsWith(pathSeparator)) { baseIsFile = false; } StringBuilder relative = new StringBuilder(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append("..").append(pathSeparator); } } relative.append(targetPath.substring(common.length())); return relative.toString(); } }