Here you can find the source of getRelativePath(File root, File target, String fileSeparator)
public static String getRelativePath(File root, File target, String fileSeparator)
//package com.java2s; /*//from w w w. j ava 2 s. c o m * This file is part of the Jose Project * see http://jose-chess.sourceforge.net/ * (c) 2002-2006 Peter Sch?fer * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * */ import java.io.*; import java.util.Vector; public class Main { public static String getRelativePath(File root, File target, String fileSeparator) { if (fileSeparator == null) fileSeparator = File.separator; Vector rootHierarchy = new Vector(); for (File dir = root; dir != null; dir = dir.getParentFile()) rootHierarchy.add(dir); StringBuffer buf = new StringBuffer(); for (; target != null; target = target.getParentFile()) { int idx = rootHierarchy.indexOf(target); if (idx == 0) { // root is a direct parent of target if (buf.length() == 0) buf.append("."); break; } else if (idx > 0) { // there is a common parent while (idx-- > 0) { if (buf.length() > 0) buf.insert(0, fileSeparator); buf.insert(0, ".."); } break; } else { // climb one up if (buf.length() > 0) buf.insert(0, fileSeparator); buf.insert(0, target.getName()); } } return buf.toString(); } }