Here you can find the source of relativePath(File path, File relativeTo)
Parameter | Description |
---|---|
path | The target path |
relativeTo | The path that the target path should be relative to |
public static File relativePath(File path, File relativeTo)
//package com.java2s; //License from project: Apache License import java.io.File; public class Main { /**// w w w.ja v a2 s .c o m * Calculates the relative path of one path relative to another * * @param path The target path * @param relativeTo The path that the target path should be * relative to * @return A path that is pointing to the target path but is * relative to the relativeTo path */ public static File relativePath(File path, File relativeTo) { File tmpPath = path; File tmpRelativeTo = relativeTo; if (tmpRelativeTo != null) { String t1 = getFirstPart(tmpPath); String t2 = getFirstPart(tmpRelativeTo); while (t2.equals(t1)) { tmpPath = getTail(tmpPath); tmpRelativeTo = getTail(tmpRelativeTo); t1 = getFirstPart(tmpPath); t2 = getFirstPart(tmpRelativeTo); } } while (tmpRelativeTo != null) { tmpPath = new File("..", tmpPath.getPath()); tmpRelativeTo = tmpRelativeTo.getParentFile(); } return tmpPath; } /** * Get the first part of a file path, which is the root directory * or the file name if the path contains no directory * * @param path * @return The first part of a file path */ public static String getFirstPart(File path) { String first = ""; File tmp = path; while (tmp != null) { first = tmp.getName(); tmp = tmp.getParentFile(); } return first; } /** * Get everything but the first part of a file path * * @param path * @return Everything but the first part of the file path */ public static File getTail(File path) { if (path.getParentFile() == null) { return null; } else { String first = getFirstPart(path); return new File(path.getPath().substring(first.length() + 1)); } } }