Java Relative Path Get relativePath(File IncludedFile, File UpperDirectory)

Here you can find the source of relativePath(File IncludedFile, File UpperDirectory)

Description

{ method

License

Apache License

Parameter

Parameter Description
IncludedFile non-null existing file in UpperDirectory
UpperDirectory non-null existing directory

Return

string representing the path of the fiel relatove to the directory }

Declaration

public static String relativePath(File IncludedFile, File UpperDirectory) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    /**/*from   w ww . ja v a  2  s . com*/
     * { method
     *
     * @param IncludedFile   non-null existing file in UpperDirectory
     * @param UpperDirectory non-null existing directory
     * @return string representing the path of the fiel relatove to the directory
     *         }
     * @name relativePath
     * @function return a string representing the path of included file ret
     */
    public static String relativePath(File IncludedFile, File UpperDirectory) {
        if (!IncludedFile.exists())
            throw new IllegalArgumentException(
                    "requested file '" + IncludedFile.getAbsolutePath() + "' does not exist");
        if (!UpperDirectory.exists())
            throw new IllegalArgumentException(
                    "requested file '" + UpperDirectory.getAbsolutePath() + "' does not exist");
        if (!UpperDirectory.isDirectory())
            throw new IllegalArgumentException(
                    "requested directory '" + UpperDirectory.getAbsolutePath() + "' is not a directory");
        String ret = IncludedFile.getName();
        File Test = new File(IncludedFile.getParent());
        while (Test != null) {
            if (Test.equals(UpperDirectory))
                break;
            ret = Test.getName() + "/" + ret;
            Test = new File(Test.getParent());
        }
        if (Test == null)
            throw new IllegalArgumentException("directory '" + UpperDirectory.getAbsolutePath()
                    + "' is not a parent of file '" + IncludedFile.getAbsolutePath() + "'");
        return (ret);
    }
}

Related

  1. relativePath(File baseDir, File storeFile)
  2. relativePath(File descendant, File root)
  3. relativePath(File file, String path)
  4. relativePath(File from, File to)
  5. relativePath(File home, File f)
  6. relativePath(File parent, File child)
  7. relativePath(File parent, File child)
  8. relativePath(File path, File relativeTo)
  9. relativePath(File root, File node)