Here you can find the source of relativePath(File src, File dest)
public static String relativePath(File src, File dest)
//package com.java2s; /*####################################################### * * Maintained by Gregor Santner, 2017- * https://gsantner.net//*from w w w. j a v a2 s .c o m*/ * * License: Apache 2.0 * https://github.com/gsantner/opoc/#licensing * https://www.apache.org/licenses/LICENSE-2.0 * #########################################################*/ import java.io.File; import java.io.IOException; import java.util.regex.Pattern; public class Main { public static String relativePath(File src, File dest) { try { String[] srcSplit = (src.isDirectory() ? src : src.getParentFile()).getCanonicalPath() .split(Pattern.quote(File.separator)); String[] destSplit = dest.getCanonicalPath().split(Pattern.quote(File.separator)); StringBuilder sb = new StringBuilder(); int i = 0; for (; i < destSplit.length && i < srcSplit.length; ++i) { if (!destSplit[i].equals(srcSplit[i])) break; } if (i != srcSplit.length) { for (int iUpperDir = i; iUpperDir < srcSplit.length; ++iUpperDir) { sb.append(".."); sb.append(File.separator); } } for (; i < destSplit.length; ++i) { sb.append(destSplit[i]); sb.append(File.separator); } if (!dest.getPath().endsWith("/") && !dest.getPath().endsWith("\\")) { sb.delete(sb.length() - File.separator.length(), sb.length()); } return sb.toString(); } catch (IOException | NullPointerException exception) { return null; } } }