Here you can find the source of getRelativePath(File target, File relativeTo)
public static String getRelativePath(File target, File relativeTo)
//package com.java2s; //License from project: Apache License import java.io.File; import java.util.ArrayList; import java.util.List; public class Main { public static String getRelativePath(File target, File relativeTo) { List<File> targetPaths = new ArrayList<File>(); List<File> relativePaths = new ArrayList<File>(); generateList(target, targetPaths); generateList(relativeTo, relativePaths); String result = ""; List<File> namedPaths = new ArrayList<File>(); namedPaths.addAll(targetPaths);//from w w w . ja va 2 s. c o m namedPaths.removeAll(relativePaths); for (int ctr = 0; ctr < namedPaths.size(); ctr++) { result = namedPaths.get(ctr).getName() + "/" + result; } result = result.substring(0, result.length() - 1); List<File> levels = new ArrayList<File>(); levels.addAll(relativePaths); levels.removeAll(targetPaths); for (int ctr = 0; ctr < levels.size() - 1; ctr++) { result = "../" + result; } return result; } private static void generateList(File currentFile, List<File> targetPaths) { while (currentFile != null) { targetPaths.add(currentFile); currentFile = currentFile.getParentFile(); } } }