Java URI to Relative URI relativize(URI base, URI child)

Here you can find the source of relativize(URI base, URI child)

Description

relativize

License

Open Source License

Declaration

public static URI relativize(URI base, URI child) 

Method Source Code

//package com.java2s;
/**// w ww. ja  v  a  2 s.  c o  m
 * Copyright (c) 2014-2015 by Wen Yu.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Any modifications to this file must keep this entire header intact.
 */

import java.net.URI;

public class Main {
    public static URI relativize(URI base, URI child) {
        // Normalize paths to remove . and .. segments
        base = base.normalize();
        child = child.normalize();

        // Split paths into segments
        String[] bParts = base.getPath().split("/");
        String[] cParts = child.getPath().split("/");

        // Discard trailing segment of base path
        if (bParts.length > 0 && !base.getPath().endsWith("/")) {
            System.arraycopy(bParts, 0, bParts, 0, bParts.length - 1);
            // JDK1.6+ 
            //bParts = java.util.Arrays.copyOf(bParts, bParts.length - 1);
        }

        // Remove common prefix segments
        int i = 0;

        while (i < bParts.length && i < cParts.length && bParts[i].equals(cParts[i])) {
            i++;
        }

        // Construct the relative path
        StringBuilder sb = new StringBuilder();

        for (int j = 0; j < (bParts.length - i); j++) {
            sb.append("../");
        }

        for (int j = i; j < cParts.length; j++) {
            if (j != i) {
                sb.append("/");
            }
            sb.append(cParts[j]);
        }

        return URI.create(sb.toString());
    }
}

Related

  1. relativeConfig(URI uri)
  2. relativeFileToURI(File file)
  3. relativePath(final URI baseURI, final URI pathURI)
  4. relativeURI(String basePath, String path)
  5. relativize(URI base, URI child)
  6. relativize(URI base, URI target)
  7. relativize(URI basePath, File path)
  8. relativize(URI baseUri, File f)
  9. relativize(URI baseURI, URI uriToRelativize)