Here you can find the source of getRelativePath(Path file, Path baseDir)
public static String getRelativePath(Path file, Path baseDir)
//package com.java2s; //License from project: Open Source License import java.nio.file.Path; public class Main { public final static char SLASH_CHAR = '/'; public final static char BACK_SLASH_CHAR = '\\'; public static String getRelativePath(Path file, Path baseDir) { return getRelativePath(file != null ? file.toString() : null, baseDir != null ? baseDir.toString() : null); }//from ww w . j a v a2 s .com public static final String getRelativePath(String path, String baseDirPath) { return getRelativePath(path, baseDirPath, SLASH_CHAR); } public static final String getRelativePath(String path, String baseDirPath, char separator) { if (path == null) { return path; } String p = normalise(path, separator); if (baseDirPath == null) { return p; } String base = normalise(baseDirPath, separator); base = trimTrailingSeparator(base, separator); if (p.equals(base) || base.length() >= p.length()) { return p; } if (p.startsWith(base)) { String relativePath = p.substring(base.length()); relativePath = trimLeadingSeparator(relativePath, separator); return relativePath; } return p; } public static final String normalise(String path) { return normalise(path, BACK_SLASH_CHAR, SLASH_CHAR); } public static final String normalise(String path, char separator) { return normalise(path, separator, separator); } public static final String normalise(String path, char separator, char newSeparator) { if (path != null) { String p = path.trim(); if (separator != newSeparator) { p = p.replace(separator, newSeparator); } p.replaceAll("\\" + newSeparator + "{2,}", "\\" + newSeparator); return p; } return null; } public static final String trimTrailingSeparator(String path, char separator) { if (path != null) { String p = normalise(path, separator); if (p.length() > 1) { return p.replaceAll("\\" + separator + "+$", ""); } else { return p; } } return null; } public static boolean equals(String a, String b) { String sa = b == null ? null : normalise(b); String sb = a == null ? null : normalise(a); if (sa != null && sb != null) { return sa.equals(sb); } else if (sa == null && sb == null) { return true; } return false; } public static final String trimLeadingSeparator(String path, char separator) { if (path != null) { String p = normalise(path, separator); if (p.length() > 1) { return p.replaceAll("^\\" + separator + "+", ""); } else { return p; } } return null; } }