Java URI to Relative URI getRelativePath(URI targetUri, URI baseUri)

Here you can find the source of getRelativePath(URI targetUri, URI baseUri)

Description

Finds the relative path from the baseUri to the target URI.

License

Common Public License

Parameter

Parameter Description
targetUri The URI of the resource to get the relative path to.
baseUri URI of the directory the path should be relative to.

Declaration

public static String getRelativePath(URI targetUri, URI baseUri) 

Method Source Code

//package com.java2s;
//License from project: Common Public License 

import java.net.JarURLConnection;

import java.net.URI;

public class Main {
    /**//  w  w w. j  a  va2 s .c  o m
     * Finds the relative path from the baseUri to the target URI.
     * @param targetUri The URI of the resource to get the relative path to.
     * @param baseUri URI of the directory the path should be relative to. 
     * @return
     */
    public static String getRelativePath(URI targetUri, URI baseUri) {

        //  We need the -1 argument to split to make sure we get a trailing 
        //  "" token if the base ends in the path separator and is therefore
        //  a directory. We require directory paths to end in the path
        //  separator -- otherwise they are indistinguishable from files.
        String pathSeparator = "/";
        String targetPath = targetUri.getPath();
        String[] base;
        String[] target;
        if (baseUri.toString().startsWith("jar:")) {
            try {
                JarURLConnection conn = (JarURLConnection) (baseUri.toURL().openConnection());
                String entryName = conn.getEntryName();
                if (entryName == null)
                    entryName = pathSeparator;
                base = entryName.split(pathSeparator);
                if (!targetUri.toString().startsWith("jar:")) {
                    throw new RuntimeException(
                            "Base URI is a jar URI but target URI is not, got \"" + targetUri.toString() + "\"");
                }
                conn = (JarURLConnection) (targetUri.toURL().openConnection());
                entryName = conn.getEntryName();
                if (entryName == null)
                    entryName = pathSeparator;
                targetPath = entryName;
                target = conn.getEntryName().split(pathSeparator);
            } catch (Exception e) {
                throw new RuntimeException("Unexpected exception from jar: URL: " + e.getMessage());
            }

        } else {
            base = baseUri.getPath().split(pathSeparator);
            target = targetPath.split(pathSeparator);
        }

        //  First get all the common elements. Store them as a string,
        //  and also count how many of them there are. 
        String common = "";
        int commonIndex = 0;
        for (int i = 0; i < target.length && i < base.length; i++) {
            if (target[i].equals(base[i])) {
                common += target[i] + pathSeparator;
                commonIndex++;
            } else
                break;
        }

        if (commonIndex == 0) {
            //  Whoops -- not even a single common path element. This most
            //  likely indicates differing drive letters, like C: and D:. 
            //  These paths cannot be relativized. Return the target path.
            return targetPath;
        }

        String relative = "";
        if (base.length == commonIndex) {
            // Do nothing.
        } else {
            int numDirsUp = base.length - commonIndex;
            //  The number of directories we have to backtrack is the length of 
            //  the base path MINUS the number of common path elements, minus
            //  one because the last element in the path isn't a directory.
            for (int i = 1; i <= (numDirsUp); i++) {
                relative += ".." + pathSeparator;
            }
        }
        //if we are comparing directories then we 
        if (targetPath.length() > common.length()) {
            //it's OK, it isn't a directory
            relative += targetPath.substring(common.length());
        }

        return relative;
    }
}

Related

  1. getRedirectUri(URI uri, String location)
  2. getRelativeLocalURI(String suffix)
  3. getRelativeName(File file, URI directory)
  4. getRelativePath(URI base, File file)
  5. getRelativePath(URI targetURI, URI baseURI)
  6. getRelativeURI(String href)
  7. getRelativeURI(URI base, URI uri)
  8. getRelativeURI(URI repositoryXml, URI bundleJar)