集册 Java实例教程 获取相对路径

获取相对路径

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

465
获取相对路径

/*******************************************************************************

 * Copyright (c) 2006, 2010 Soyatec (http://www.soyatec.com) and others.       *

 * 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                                   *  

 * Contributors:                                                               *  

 *     Soyatec - initial API and implementation                                * 

 *******************************************************************************/

//package com.nowjava;

import java.io.File;
/** 
来 自 
时   代     Java  公  众  号 - nowjava.com
**/


public class Main {

    public static final String BACKWARD_SLASH = "\\";

    public static final String FORWARD_SLASH = "/";

    public static final String RELATIVE_PATH_SIG = "../";


    public static String getRelativePath(String source, String target) {

        if (source == null || target == null) {

            return target;

        }//来 自 N o w  J a v a  . c o m

        File sourceFile = new File(source);

        if (!sourceFile.exists()) {

            return target;

        }

        File targetFile = new File(target);

        if (!targetFile.exists()) {

            return target;

        }

        source = switchToForwardSlashes(source);

        target = switchToForwardSlashes(target);

        int index = target.indexOf(FORWARD_SLASH);

        String container = null;

        while (index != -1) {

            container = target.substring(0, index);

            if (!source.startsWith(container + FORWARD_SLASH)) {

                break;

            }

            source = source.substring(index + 1);

            target = target.substring(index + 1);

            index = target.indexOf(FORWARD_SLASH);

        }

        index = source.indexOf(FORWARD_SLASH);

        while (index != -1) {

            target = RELATIVE_PATH_SIG + target;

            source = source.substring(index + 1);

            in
展开阅读全文