From b2b7e974a387cddb07fba15738074ac09ceac1a1 Mon Sep 17 00:00:00 2001 From: samskivert Date: Wed, 16 Jun 2010 23:38:35 +0000 Subject: [PATCH] Added getCanonicalPathElements() and computeRelativePath(). From Dave. git-svn-id: https://samskivert.googlecode.com/svn/trunk@2791 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- src/java/com/samskivert/net/PathUtil.java | 54 +++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/java/com/samskivert/net/PathUtil.java b/src/java/com/samskivert/net/PathUtil.java index a67b53ff..4640ab81 100644 --- a/src/java/com/samskivert/net/PathUtil.java +++ b/src/java/com/samskivert/net/PathUtil.java @@ -20,6 +20,9 @@ package com.samskivert.net; +import java.io.File; +import java.io.IOException; + /** * Path related utility functions. */ @@ -68,4 +71,55 @@ public class PathUtil return source + "/" + affix; } } + + /** + * Gets the individual path elements building up the canonical path to the given file. + */ + public static String[] getCanonicalPathElements (File file) + throws IOException + { + file = file.getCanonicalFile(); + + // If we were a file, get its parent + if (!file.isDirectory()) { + file = file.getParentFile(); + } + + return file.getPath().split(File.separator); + } + + /** + * Computes a relative path between to Files + * + * @param file the file we're referencing + * @param relativeTo the path from which we want to refer to the file + */ + public static String computeRelativePath (File file, File relativeTo) + throws IOException + { + String[] realDirs = getCanonicalPathElements(file); + String[] relativeToDirs = getCanonicalPathElements(relativeTo); + + // Eliminate the common root + int common = 0; + for (; common < realDirs.length && common < relativeToDirs.length; common++) { + if (!realDirs[common].equals(relativeToDirs[common])) { + break; + } + } + + String relativePath = ""; + + // For each remaining level in the file path, add a .. + for (int ii = 0; ii < (realDirs.length - common); ii++) { + relativePath += ".." + File.separator; + } + + // For each level in the resource path, add the path + for (; common < relativeToDirs.length; common++) { + relativePath += relativeToDirs[common] + File.separator; + } + + return relativePath; + } }