Here you can find the source of getRelativeAncestor(File ancestor, File descendant)
Parameter | Description |
---|---|
IllegalArgumentException | If the given descendant is notactually a descendant of the given ancestor. |
private static String getRelativeAncestor(File ancestor, File descendant)
//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; } }