get Relative Path - Java File Path IO

Java examples for File Path IO:Path

Description

get Relative Path

Demo Code

/*******************************************************************************
 * 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.java2s;
import java.io.File;

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;
        }// w  ww .  j a v  a 2 s  . 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);
            index = source.indexOf(FORWARD_SLASH);
        }
        return target;
    }

    /**
     * Switch to file path slashes
     */
    public static String switchToForwardSlashes(String path) {
        path = path.replace(File.separatorChar, FORWARD_SLASH.charAt(0));
        path = path.replace(BACKWARD_SLASH.charAt(0),
                FORWARD_SLASH.charAt(0));
        return path;
    }
}

Related Tutorials