in commons-vfs2/src/main/java/org/apache/commons/vfs2/provider/AbstractFileName.java [315:363]
public String getRelativeName(final FileName name) throws FileSystemException {
final String path = name.getPath();
// Calculate the common prefix
final int basePathLen = getPath().length();
final int pathLen = path.length();
// Deal with root
if (basePathLen == 1 && pathLen == 1) {
return ".";
}
if (basePathLen == 1) {
return path.substring(1);
}
final int maxlen = Math.min(basePathLen, pathLen);
int pos = 0;
while (pos < maxlen && getPath().charAt(pos) == path.charAt(pos)) {
pos++;
}
if (pos == basePathLen && pos == pathLen) {
// Same names
return ".";
}
if (pos == basePathLen && pos < pathLen && path.charAt(pos) == SEPARATOR_CHAR) {
// A descendent of the base path
return path.substring(pos + 1);
}
// Strip the common prefix off the path
final StringBuilder buffer = new StringBuilder();
if (pathLen > 1 && (pos < pathLen || getPath().charAt(pos) != SEPARATOR_CHAR)) {
// Not a direct ancestor, need to back up
pos = getPath().lastIndexOf(SEPARATOR_CHAR, pos);
buffer.append(path.substring(pos));
}
// Prepend a '../' for each element in the base path past the common
// prefix
buffer.insert(0, "..");
pos = getPath().indexOf(SEPARATOR_CHAR, pos + 1);
while (pos != -1) {
buffer.insert(0, "../");
pos = getPath().indexOf(SEPARATOR_CHAR, pos + 1);
}
return buffer.toString();
}