Java Path Relative getRelativeAncestor(File ancestor, File descendant)

Here you can find the source of getRelativeAncestor(File ancestor, File descendant)

Description

Get a relative path pointing from a descendant to an ancestor.

License

Open Source License

Exception

Parameter Description
IllegalArgumentException If the given descendant is notactually a descendant of the given ancestor.

Return

A relative File, pointing from the descendant to the ancestor.

Declaration

private static String getRelativeAncestor(File ancestor, File descendant) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.*;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;

public class Main {
    /**/*from w  ww.  java  2 s  .c o m*/
     * Get a relative path pointing from a descendant to an ancestor.
     * @return A relative File, pointing from the descendant to the ancestor.
     * @throws IllegalArgumentException If the given descendant is not
     * actually a descendant of the given ancestor.
     */
    private static String getRelativeAncestor(File ancestor, File descendant) {
        List ancestors = getAncestors(descendant);
        if (!ancestors.contains(ancestor)) {
            throw new IllegalArgumentException("The file \""
                    + descendant.getPath() + "\" "
                    + "does not have ancestor \"" + ancestor.getPath()
                    + "\".");
        }
        // Move an iterator to the location of the ancestor:
        Iterator i = ancestors.iterator();
        File f;
        do {
            f = (File) i.next();
        } while (!ancestor.equals(f));

        // Construct a path String from the remaining iterations:
        StringBuffer path = new StringBuffer();
        while (i.hasNext()) {
            i.next();
            path.append("..");
            if (i.hasNext()) {
                path.append(File.separatorChar);
            }
        }
        return path.toString();
    }

    /**
     * Get a List of ancestor Files of a given File, in order from highest to
     * lowest ancestor and not including the File itself.
     */
    static List<File> getAncestors(File file) {
        LinkedList<File> list = new LinkedList<File>();
        file = file.getParentFile();
        if (file == null) {
            return list;
        }
        do {
            list.addFirst(file);
            file = file.getParentFile();
        } while (file != null);
        return list;
    }
}

Related

  1. getRelative(File base, File path)
  2. getRelative(File base, File path)
  3. getRelative(String basedir, String child)
  4. getRelativeBaseDirectory(final File processedFile)
  5. getRelativeChildDirectory(String parent, String child)
  6. getRelativeDirectoryPath(String in_filePath, String in_basePath)
  7. getRelativeFile(File parent, final String s2)