Here you can find the source of makeRelativePath(File from, File to)
public static String makeRelativePath(File from, File to)
//package com.java2s; /*//from w w w.j a va 2s . c o m * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ import java.io.File; import java.io.IOException; public class Main { public static String makeRelativePath(File from, File to) { File f = makeRelativeFile(from, to); return (f != null ? f.getPath() : null); } public static String makeRelativePath(File from, String to) { File f = makeRelativeFile(from, new File(to)); return (f != null ? f.getPath() : null); } /** * Attempts to make a path relative to a particular directory. * * @param from the directory from which 'to' should be relative * @param to an absolute path which will be returned so that it is relative to * 'from' * @return the relative path, if possible; null otherwise */ public static File makeRelativeFile(File from, File to) { // Keep ripping off directories from the 'from' path until the 'from' path // is a prefix of the 'to' path. // String toPath = tryMakeCanonical(to).getAbsolutePath(); File currentFrom = tryMakeCanonical(from.isDirectory() ? from : from.getParentFile()); int numberOfBackups = 0; while (currentFrom != null) { String currentFromPath = currentFrom.getPath(); if (toPath.startsWith(currentFromPath)) { // Found a prefix! // break; } else { ++numberOfBackups; currentFrom = currentFrom.getParentFile(); } } if (currentFrom == null) { // Cannot make it relative. // return null; } // Find everything to the right of the common prefix. // String trailingToPath = toPath.substring(currentFrom.getAbsolutePath().length()); if (currentFrom.getParentFile() != null && trailingToPath.length() > 0) { trailingToPath = trailingToPath.substring(1); } File relativeFile = new File(trailingToPath); for (int i = 0; i < numberOfBackups; ++i) { relativeFile = new File("..", relativeFile.getPath()); } return relativeFile; } /** * Attempts to find the canonical form of a file path. * * @return the canonical version of the file path, if it could be computed; * otherwise, the original file is returned unmodified */ public static File tryMakeCanonical(File file) { try { return file.getCanonicalFile(); } catch (IOException e) { return file; } } }