集册 Java实例教程 返回表示路径相对于原点的位置的相对路径

返回表示路径相对于原点的位置的相对路径

欢马劈雪     最近更新时间:2020-01-02 10:19:05

704
返回表示相对于原点的路径位置的相对路径
/**来 自 时 代      J a v a   公   众 号 - nowjava.com**/

/*

 * 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.nowjava;


import java.util.StringTokenizer;


public class Main {

    /**

     * Returns the relative path that expresses the location of <code>path</code> seen as relative to <code>origin</code>

     * @param origin Where to make relative to

     * @param path The full path

     * @return The relative path from <code>origin</code> to <code>path</code>

     */

    public static String makeRelative(String origin, String path) {

        boolean trailingSlash = path.endsWith("/");

        StringBuffer sb = new StringBuffer(40);

        StringTokenizer originTokenizer = new StringTokenizer(origin, "/",

                false);

        StringTokenizer pathTokenizer = new StringTokenizer(path, "/",

                false);


        // Walk through the parts that are in common

        String firstTokenNotInCommon = null;

        while (originTokenizer.hasMoreTokens()

                && pathTokenizer.hasMoreTokens()

                && firstTokenNotInCommon == null) {

            firstTokenNotInCommon = pathTokenizer.nextToken();
            /* from 
            nowjava - 时  代  Java*/

            if (originTokenizer.nextToken().equals(firstTokenNotInCommon))

                firstTokenNotInCommon = null;

        }


        // Find number of elements that aren't in common, and print a '..' for each

        int stepsBack = originTokenizer.countTokens();

        if (firstTokenNotInCommon != null)

            stepsBack++;

        for (int i = 0; i < stepsBack; i++) {

            sb.append("..");

            if (trailingSlash || pathTokenizer.hasMoreTokens()

                    || firstTokenNotInCommon != null || i < stepsBack - 1)

                sb.append('/');

        }


        // Print the rest of path

        if (firstTokenNotInCommon != null) {

            sb.append(firstTokenNotInCommon);

            if (trailingSlash || pathTokenizer.hasMore
展开阅读全文