Here you can find the source of getRelativePath(String filePath, String basePath)
public static String getRelativePath(String filePath, String basePath)
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.IOException; import java.util.regex.Pattern; public class Main { public static String getRelativePath(String filePath, String basePath) { File target = new File(filePath); File base = new File(basePath); StringBuilder result = new StringBuilder(); try {//from www. j a v a 2s .c om String[] baseComponents = base.getCanonicalPath().split(Pattern.quote(File.separator)); String[] targetComponents = target.getCanonicalPath().split(Pattern.quote(File.separator)); // skip common components int index = 0; for (; index < targetComponents.length && index < baseComponents.length; ++index) { if (!targetComponents[index].equals(baseComponents[index])) { break; } } if (index != baseComponents.length) { // backtrack to base directory for (int i = index; i < baseComponents.length; ++i) { result.append(".."); result.append(File.separator); } } for (; index < targetComponents.length; ++index) { result.append(targetComponents[index]); result.append(File.separator); } if (!target.getPath().endsWith("/") && !target.getPath().endsWith("\\")) { // remove final path separator result.delete(result.length() - "/".length(), result.length()); } } catch (IOException e) { result.append(filePath); } return result.toString(); } }