Java URI to Relative URI getRelativePath(URI base, File file)

Here you can find the source of getRelativePath(URI base, File file)

Description

Return the path for the file relative to the base uri.

License

Open Source License

Parameter

Parameter Description
base the base url.
file the file location to get the relative path for.

Return

the relative path.

Declaration

public static String getRelativePath(URI base, File file) 

Method Source Code


//package com.java2s;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.StringTokenizer;

public class Main {
    /**//ww  w.  j  a  va  2 s  . c  o m
     * Return the path for the file relative to the base uri.
     *
     * @param base the base url.
     * @param file the file location to get the relative path for.
     *
     * @return the relative path.
     */
    public static String getRelativePath(URI base, File file) {
        return toString(getRelativeURI(base, file.toURI()));
    }

    /**
     * Creates a String from a URI, the URI can be relative or absolute, the URI is decoded.
     *
     * TODO Why can't I just return uri.toString()???
     *
     * @param uri the URI to return the string representation for.
     * @return a string representation of the URI.
     */
    public static String toString(URI uri) {
        StringBuffer buffer = new StringBuffer();
        if (uri.getScheme() != null) {
            buffer.append(uri.getScheme());
            buffer.append(":");
        }
        buffer.append(uri.getSchemeSpecificPart());
        if (uri.getFragment() != null) {
            buffer.append("#");
            buffer.append(uri.getFragment());
        }
        return buffer.toString();
    }

    /**
     * Return the uri for the uri relative to the base uri.
     *
     * @param base the base uri.
     * @param uri the file location to get the relative path for.
     *
     * @return the relative uri.
     */
    public static URI getRelativeURI(URI base, URI uri) {
        if (base != null && uri != null && (uri.getScheme() == null || uri.getScheme().equals(base.getScheme()))) {
            StringTokenizer baseParts = tokenizeBase(base);
            StringTokenizer uriParts = new StringTokenizer(uri.getSchemeSpecificPart(), "/");
            StringBuffer relativePath = new StringBuffer();
            String part = null;
            boolean first = true;
            if (!baseParts.hasMoreTokens()) {
                return uri;
            }
            while (baseParts.hasMoreTokens() && uriParts.hasMoreTokens()) {
                String baseDir = baseParts.nextToken();
                part = uriParts.nextToken();
                if ((baseDir.equals(part) && baseDir.contains(":")) && first) {
                    baseDir = baseParts.nextToken();
                    part = uriParts.nextToken();
                }
                if (!baseDir.equals(part)) { // || (baseDir.equals(part) && baseDir.contains(":"))) {
                    if (first) {
                        return uri;
                    }
                    relativePath.append("../");
                    break;
                }
                part = null;
                first = false;
            }
            while (baseParts.hasMoreTokens()) {
                relativePath.append("../");
                baseParts.nextToken();
            }
            if (part != null) {
                relativePath.append(part);
                if (uriParts.hasMoreTokens()) {
                    relativePath.append("/");
                }
            }
            while (uriParts.hasMoreTokens()) {
                relativePath.append(uriParts.nextToken());
                if (uriParts.hasMoreTokens()) {
                    relativePath.append("/");
                }
            }
            return createURI(relativePath.toString());
        }
        return uri;
    }

    private static StringTokenizer tokenizeBase(URI uri) {
        String scheme = uri.getSchemeSpecificPart();
        int index = scheme.lastIndexOf("/");
        if (index != -1) {
            scheme = scheme.substring(0, index + 1);
        }
        return new StringTokenizer(scheme, "/");
    }

    /**
     * Creates a URI from a path, the path can be relative or absolute, '\' and '/' are normalised.
     *
     * @param path the path to create the URI for.
     * @return a new URI.
     */
    public static URI createURI(String path) {
        path = path.replace('\\', '/');
        return URI.create(encodeURI(path));
    }

    private static String encodeURI(String url) {
        StringBuffer uri = new StringBuffer(url.length());
        int length = url.length();
        for (int i = 0; i < length; i++) {
            char c = url.charAt(i);

            switch (c) {
            case '!':
            case '#':
            case '$':
            case '%':
            case '&':
            case '\'':
            case '(':
            case ')':
            case '*':
            case '+':
            case ',':
            case '-':
            case '.':
            case '/':
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case ':':
            case ';':
            case '=':
            case '?':
            case '@':
            case 'A':
            case 'B':
            case 'C':
            case 'D':
            case 'E':
            case 'F':
            case 'G':
            case 'H':
            case 'I':
            case 'J':
            case 'K':
            case 'L':
            case 'M':
            case 'N':
            case 'O':
            case 'P':
            case 'Q':
            case 'R':
            case 'S':
            case 'T':
            case 'U':
            case 'V':
            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
            case '[':
            case ']':
            case '_':
            case 'a':
            case 'b':
            case 'c':
            case 'd':
            case 'e':
            case 'f':
            case 'g':
            case 'h':
            case 'i':
            case 'j':
            case 'k':
            case 'l':
            case 'm':
            case 'n':
            case 'o':
            case 'p':
            case 'q':
            case 'r':
            case 's':
            case 't':
            case 'u':
            case 'v':
            case 'w':
            case 'x':
            case 'y':
            case 'z':
            case '~':
                uri.append(c);
                break;
            default:
                StringBuffer result = new StringBuffer(3);
                String s = String.valueOf(c);
                try {
                    byte[] data = s.getBytes("UTF8");
                    for (int j = 0; j < data.length; j++) {
                        result.append('%');
                        String hex = Integer.toHexString(data[j]);
                        result.append(hex.substring(hex.length() - 2));
                    }
                    uri.append(result.toString());
                } catch (UnsupportedEncodingException ex) {
                    // should never happen
                }
            }
        }

        return uri.toString();
    }
}

Related

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