Java Path Relative Get getRelativePath(String base, String fullPath)

Here you can find the source of getRelativePath(String base, String fullPath)

Description

Returns fullPath relative to base if base is indeed a sudirectory of fullpath.

License

Open Source License

Parameter

Parameter Description
base base directory
fullPath to be expressed as a relative path

Return

relative path if base is a subdirectory of fullpath

Declaration

public static String getRelativePath(String base, String fullPath) 

Method Source Code

//package com.java2s;
/**//from   ww w .  j a va  2 s. c  o  m
 * A small collection of useful helper methods.
 *
 * @author Olivier Wehner
 * <!--
 *  FAR - Find And Replace
 *  Copyright (C) 2009,  Olivier Wehner
    
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
    
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *  -->
 */

import java.io.File;

public class Main {
    /**
     * Returns fullPath relative to base if base is indeed a sudirectory of fullpath.
     * Returns fullPath unchanged othewise.
     * @param base base directory
     * @param fullPath to be expressed as a relative path
     * @return relative path if base is a subdirectory of fullpath
     */
    public static String getRelativePath(String base, String fullPath) {
        if (fullPath == null)
            return null;
        if (base == null || !fullPath.startsWith(base)) {
            return fullPath;
        }
        String result = fullPath.substring(base.length());
        if (result.length() == 0) {
            return ".";
        } else if (result.startsWith(File.separator)) {
            return result.substring(1); // ommit the leading slash
        } else {
            return result;
        }

    }
}

Related

  1. getRelativePath(final File from, final File to)
  2. getRelativePath(final File fromFile, final File toFile)
  3. getRelativePath(final File parentDir, final File file)
  4. getRelativePath(final File parentDirectory, final File file)
  5. getRelativePath(final String base, final File targetFile)
  6. getRelativePath(String base, String relative, boolean isBaseFile)
  7. getRelativePath(String baseFullPath, File file)
  8. getRelativePath(String basePath, String path)
  9. getRelativePath(String basePath, String pathToRelativize)