Java Path Relative Get getRelativePathToBase(File path, File basePath)

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

Description

Returns the relative path of a path from a base path.

License

Open Source License

Parameter

Parameter Description
path a path
basePath the base path

Return

a relative path

Declaration

public static String getRelativePathToBase(File path, File basePath) 

Method Source Code

//package com.java2s;
// are made available under the terms of the Eclipse Public License v1.0

import java.io.File;

public class Main {
    /**//from  w  w  w  . ja  v a 2 s  .c om
     * Returns the relative path of a path from a base path.
     * 
     * @param path
     *            a path
     * @param basePath
     *            the base path
     * @return a relative path
     */
    public static String getRelativePathToBase(File path, File basePath) {
        try {
            String dir = path.toURL().toExternalForm();
            String baseDir = basePath.toURL().toExternalForm();
            StringBuffer result = new StringBuffer();
            if (dir.indexOf(baseDir) == 0) {
                String delta = dir.substring(baseDir.length());
                for (int i = 0; i < delta.length(); i++) {
                    if (delta.charAt(i) == '/') {
                        result.append("../"); //$NON-NLS-1$
                    }
                }
            }
            return result.toString();
        } catch (Exception e) {
            return ""; //$NON-NLS-1$
        }
    }
}

Related

  1. getRelativePath(String target, String base)
  2. getRelativePath(String targetPath, String basePath, String pathSeparator)
  3. getRelativePath(String targetPath, String basePath, String pathSeparator)
  4. getRelativePathOfZipEntry(final File fileToZip, final File base)
  5. getRelativePathRecursive(File file, File baseDir, String prefix)
  6. getRelativePathToTestModule()
  7. getRelativePathToWWW(String fileName)