Here you can find the source of getRelativePath(File file, File baseDir)
public static String getRelativePath(File file, File baseDir)
//package com.java2s; //License from project: Apache License import java.io.File; public class Main { public static String getRelativePath(File file, File baseDir) { if (isFileInDirRecursive(file, baseDir)) { return baseDir.toURI().relativize(file.toURI()).getPath(); } else {//from ww w . j a v a 2 s . c om return getRelativePathRecursive(file, baseDir, ""); } } protected static boolean isFileInDirRecursive(File file, File dir) { if (file.getParentFile() != null) { return file.getParentFile().equals(dir) || isFileInDirRecursive(file.getParentFile(), dir); } return false; } private static String getRelativePathRecursive(File file, File baseDir, String prefix) { if (isFileInDirRecursive(file, baseDir)) { return prefix + baseDir.toURI().relativize(file.toURI()).getPath(); } else if (baseDir.getParentFile() != null) { return prefix + getRelativePathRecursive(file, baseDir.getParentFile(), "../"); } else { return file.toURI().toString(); } } }