Java examples for File Path IO:Path
relative Path
//package com.java2s; public class Main { public static String relativePath(String absolutePath, String relativeTo) { String[] absoluteDirectories = absolutePath.split("\\\\"); String[] relativeDirectories = relativeTo.split("\\\\"); //Get the shortest of the two paths int length = absoluteDirectories.length < relativeDirectories.length ? absoluteDirectories.length : relativeDirectories.length; //Use to determine where in the loop we exited int lastCommonRoot = -1; int index; //Find common root for (index = 0; index < length; index++) { if (absoluteDirectories[index] .equals(relativeDirectories[index])) { lastCommonRoot = index;//from ww w.j a v a 2s . c o m } else { break; } } //Build up the relative path StringBuilder relativePath = new StringBuilder(); //Add on the .. for (index = lastCommonRoot + 1; index < absoluteDirectories.length; index++) { if (absoluteDirectories[index].length() > 0) { relativePath.append("..\\"); } } //Add on the folders for (index = lastCommonRoot + 1; index < relativeDirectories.length - 1; index++) { relativePath.append(relativeDirectories[index]).append("\\"); } relativePath .append(relativeDirectories[relativeDirectories.length - 1]); return relativePath.toString(); } }