Makes an absolute URI to the location which the given relative URI identifies, seen as relative to the given absolute URI - Java java.nio.file

Java examples for java.nio.file:Path

Description

Makes an absolute URI to the location which the given relative URI identifies, seen as relative to the given absolute URI

Demo Code

/*//w ww  .  j a va  2 s  .  co m
 * Copyright (c) 2008 Dennis Thrys?e
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */
//package com.java2s;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Iterator;

public class Main {
    /**
     * Makes an absolute URI to the location which the given relative URI identifies, seen as relative to the given
     * absolute URI
     * @param absolute Absolute part
     * @param relative Relative part
     * @return absolute concatenated path
     */
    public static String makeAbsolute(String absolute, String relative) {
        boolean trailingSlash = relative.endsWith("/");
        Stack<String> stack = new Stack<String>();

        StringTokenizer st = new StringTokenizer(absolute, "/", false);
        while (st.hasMoreTokens())
            stack.push(st.nextToken());

        st = new StringTokenizer(relative, "/", false);
        while (st.hasMoreTokens()) {
            String part = st.nextToken();
            if ("..".equals(part)) {
                if (stack.isEmpty())
                    throw new IllegalArgumentException(
                            "Relative path "
                                    + relative
                                    + " refers to a folder above root of the absolute path "
                                    + absolute);
                else
                    stack.pop();
            } else {
                if (!".".equals(part))
                    stack.push(part);
            }
        }
        StringBuffer sb = new StringBuffer(absolute.length()
                + relative.length());
        sb.append('/');
        Iterator<String> iterator = stack.iterator();
        while (iterator.hasNext()) {
            String part = iterator.next();
            sb.append(part);
            if (trailingSlash || iterator.hasNext())
                sb.append('/');
        }
        return sb.toString();
    }
}

Related Tutorials