集册 Java实例教程 相对路径

相对路径

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

494
相对路径
/*from N o w J a v a . c o m - 时代Java*/


//package com.nowjava;


public class Main {

    public static String relativePath(String absolutePath, String relativeTo) {

        String[] absoluteDirectories = absolutePath.split("\\\\");

        String[] relativeDirectories = relativeTo.split("\\\\");


        //Get the shortest of the two paths

        int length = absoluteDirectories.length < relativeDirectories.length ? absoluteDirectories.length

                : relativeDirectories.length;


        //Use to determine where in the loop we exited

        int lastCommonRoot = -1;

        int index;


        //Find common root

        for (index = 0; index < length; index++) {

            if (absoluteDirectories[index]/*n o w  j a v a  . c o m 提 供*/

                    .equals(relativeDirectories[index])) {

                lastCommonRoot = index;

            } else {

                break;

            }

        }


        //Build up the relative path

        StringBuilder relativePath = new StringBuilder();


        //Add on the ..

        for (index = lastCommonRoot + 1; index < absoluteDirectories.length; index++) {

            if (absoluteDirectories[index].length() > 0) {

                relativePath.append("..\\");

            }

        }


        //Add on the folders

        for (index = l
展开阅读全文