Here you can find the source of getRelativePath(File path, File basePath)
public static String getRelativePath(File path, File basePath)
//package com.java2s; // are made available under the terms of the Eclipse Public License v1.0 import java.io.File; public class Main { public static String getRelativePath(File path, File basePath) { try {//from w w w . j a v a 2s . c o m String dir = path.toURL().toExternalForm(); String baseDir = appendSeparator(basePath.toURL().toExternalForm(), "/"); //$NON-NLS-1$ StringBuffer result = new StringBuffer(); while (dir.indexOf(baseDir) == -1) { basePath = basePath.getParentFile(); baseDir = appendSeparator(basePath.toURL().toExternalForm(), "/"); //$NON-NLS-1$ result.append("../"); //$NON-NLS-1$ } if (dir.indexOf(baseDir) == 0) { String delta = dir.substring(baseDir.length()); result.append(delta); } return result.toString(); } catch (Exception e) { return ""; //$NON-NLS-1$ } } /** * Appends the platform specific path separator to the end of a path. * * @param path * a path name * @return the path name appended with the platform specific path separator */ public static String appendSeparator(String path) { return appendSeparator(path, File.separator); } /** * Appends the given path separator to the end of a path * * @param path * a path name * @param separator * a path separator * @return the path name appended with the given separator */ public static String appendSeparator(String path, String separator) { return path.endsWith(separator) ? path : path + separator; } }