Here you can find the source of getRelativeFile(File target, File base)
Parameter | Description |
---|---|
target | The target file |
base | The base file |
public static File getRelativeFile(File target, File base)
//package com.java2s; /**//from w w w . j a v a2s .c o m * Copyright 2009-2012 Three Crickets LLC. * <p> * The contents of this file are subject to the terms of the LGPL version 3.0: * http://www.gnu.org/copyleft/lesser.html * <p> * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly from Three Crickets * at http://threecrickets.com/ */ import java.io.File; import java.util.regex.Pattern; public class Main { /** * Returns the path of one file relative to another. * * @param target * The target file * @param base * The base file * @return The target's file relative to the base file */ public static File getRelativeFile(File target, File base) { return new File(getRelativePath(target.getAbsolutePath(), base.getAbsolutePath())); } /** * Returns the path of one file relative to another. * * @param target * The target path * @param base * The base path * @return The target's path relative to the base path */ public static String getRelativePath(String target, String base) { // See: // http://stackoverflow.com/questions/204784/how-to-construct-a-relative-path-in-java-from-two-absolute-paths-or-urls String split = Pattern.quote(File.separator); String[] baseSegments = base.split(split); String[] targetSegments = target.split(split); StringBuilder result = new StringBuilder(); // Skip common segments int index = 0; for (; index < targetSegments.length && index < baseSegments.length; ++index) { if (!targetSegments[index].equals(baseSegments[index])) break; } // Backtrack to base directory int length = baseSegments.length; if (index != length) { for (int i = index; i < length; ++i) { // "." segments have no effect if (!baseSegments[i].equals(".")) result.append(".." + File.separator); } } for (; index < targetSegments.length; ++index) result.append(targetSegments[index] + File.separator); // Remove final path separator if (!target.endsWith(File.separator)) result.delete(result.length() - 1, result.length()); return result.toString(); } }