Here you can find the source of getRelativePath(File original, File directory)
public static String getRelativePath(File original, File directory)
//package com.java2s; //License from project: Open Source License import java.io.File; public class Main { /**/* w w w .java2s .c o m*/ * Return a relative path to original as seen from given directory. * It may be absolute if they are on different drives on Windows. * All file separators will be '/' characters to make the path usable in HTML. * e.g. \photos\foo\bar\photo.jpg and \photos\foo\xyz\ => ../bar/photo.jpg */ public static String getRelativePath(File original, File directory) { String result = null; try { String o = original.getCanonicalPath(); String dir = directory.getCanonicalPath() + File.separator; // Find common prefix int lastCommon = 0; int index = dir.indexOf(File.separator); while (index >= 0) { if (!dir.regionMatches(true, lastCommon, o, lastCommon, index - lastCommon)) break; // No more matching prefix lastCommon = index; index = dir.indexOf(File.separator, index + 1); } if (lastCommon == 0) { return o; // No common prefix } StringBuffer resultbuf = new StringBuffer(o.length()); if (index > 0) { // Did not run out of directory path, build relative path // while it lasts. while (index >= 0) { resultbuf.append("../"); index = dir.indexOf(File.separator, index + 1); } } resultbuf.append(o.substring(lastCommon + 1)); result = resultbuf.toString(); } catch (Exception e) { System.out.println("getRelativePath:" + e); result = original.getAbsolutePath(); } return result.replace('\\', '/'); } }