Java Path Relative nio getRelativePath(File basePath, File path)

Here you can find the source of getRelativePath(File basePath, File path)

Description

Determine the relative path between two files.

License

Apache License

Parameter

Parameter Description
basePath a parameter
path a parameter

Return

a relative path from basePath to path

Declaration

public static String getRelativePath(File basePath, File path) 

Method Source Code

//package com.java2s;
/*/*w w w  .  ja v a  2  s.  c om*/
 * Copyright 2011 gitblit.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;

import java.io.IOException;

import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
    /**
     * Determine the relative path between two files.  Takes into account
     * canonical paths, if possible.
     *
     * @param basePath
     * @param path
     * @return a relative path from basePath to path
     */
    public static String getRelativePath(File basePath, File path) {
        Path exactBase = Paths.get(getExactFile(basePath).toURI());
        Path exactPath = Paths.get(getExactFile(path).toURI());
        if (exactPath.startsWith(exactBase)) {
            return exactBase.relativize(exactPath).toString()
                    .replace('\\', '/');
        }
        // no relative relationship
        return null;
    }

    /**
     * Returns the exact path for a file. This path will be the canonical path
     * unless an exception is thrown in which case it will be the absolute path.
     *
     * @param path
     * @return the exact file
     */
    public static File getExactFile(File path) {
        try {
            return path.getCanonicalFile();
        } catch (IOException e) {
            return path.getAbsoluteFile();
        }
    }
}

Related

  1. getFileFromBaseFileAndPathThatMayBeRelative(File baseDir, String pathThatMayBeRelative)
  2. getFileRelativeFolders(Path basePath, Path filePath)
  3. getOptionalPathRelativeToMavenProjectRoot(File absoluteFile)
  4. getRelativeFilePathToCwd(File file)
  5. getRelativePath(File baseFile, File file, String resultIfImpossible)
  6. getRelativePath(File root, File f)
  7. getRelativePath(final File file, final File baseDir)
  8. getRelativePath(Path file, Path baseDir)
  9. getRelativePath(Path rootPath, Path path)