Here you can find the source of getRelativePath(File parent, File child)
Parameter | Description |
---|---|
parent | the assumed parent (a directory) |
child | the assumed child of the parent (a directory or a file) |
Parameter | Description |
---|---|
IOException | If caused by File#getCanonicalFile. |
public static File getRelativePath(File parent, File child) throws IOException
//package com.java2s; // Licensed under the terms of GNU General Public License v3. import java.io.File; import java.io.IOException; public class Main { /**/*from w w w. jav a 2 s . c om*/ * Returns the relative path to a file with respect to a parent directory. * The method can be used to determine whether the given File objects * form a parent-child relationship. If they do form such a relationship, * the relative path from the parent to the child is returned. If they * don't form a parent-child relationship, {@code null} is returned. * * @param parent the assumed parent (a directory) * @param child the assumed child of the parent (a directory or a file) * * @return the relative path from parent to file as {@code File} object, * or {@code null} if the parent and the child are not related. * * @throws IOException If caused by {@link File#getCanonicalFile}. */ public static File getRelativePath(File parent, File child) throws IOException { // Canonicalize parent parent = parent.getCanonicalFile(); // Canonicalize the child into a local variable File file = child.getCanonicalFile(); // Create a relative path to the child. The relative path is // constructed sequentially during the loop. The construction // begins with the most nested directory and then adds new directory // the front of the existing path. File rval = new File(file.getName()); // Repeat while the file has a parent. while ((file = file.getParentFile()) != null) { // If the current directory equals to the parent directory, // then we're done. if (parent.equals(file)) { return rval; } // Prepend with the current directory rval = new File(file.getName(), rval.getPath()); } // while // The loop traversed the whole hierarchy up, and parent was not // encountered. It must be concluded that the parent wasn't really // a parent of the child. return null; } }