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

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

Description

get Relative Path

License

Open Source License

Declaration

public static String getRelativePath(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 {
    public static String getRelativePath(File path, File basePath) {
        try {//from  w w  w  .  j  a  v  a  2s .  c o  m
            String dir = path.toURL().toExternalForm();
            String baseDir = appendSeparator(basePath.toURL().toExternalForm(), "/"); //$NON-NLS-1$
            StringBuffer result = new StringBuffer();
            while (dir.indexOf(baseDir) == -1) {
                basePath = basePath.getParentFile();
                baseDir = appendSeparator(basePath.toURL().toExternalForm(), "/"); //$NON-NLS-1$
                result.append("../"); //$NON-NLS-1$
            }
            if (dir.indexOf(baseDir) == 0) {
                String delta = dir.substring(baseDir.length());
                result.append(delta);
            }
            return result.toString();
        } catch (Exception e) {
            return ""; //$NON-NLS-1$
        }
    }

    /**
     * Appends the platform specific path separator to the end of a path.
     * 
     * @param path
     *            a path name
     * @return the path name appended with the platform specific path separator
     */
    public static String appendSeparator(String path) {
        return appendSeparator(path, File.separator);
    }

    /**
     * Appends the given path separator to the end of a path
     * 
     * @param path
     *            a path name
     * @param separator
     *            a path separator
     * @return the path name appended with the given separator
     */
    public static String appendSeparator(String path, String separator) {
        return path.endsWith(separator) ? path : path + separator;
    }
}

Related

  1. getRelativePath(File parent, File child)
  2. getRelativePath(File parent, File child)
  3. getRelativePath(File parent, File f)
  4. getRelativePath(File parentDirectory, File file)
  5. getRelativePath(File path, File base)
  6. getRelativePath(File ref_file, File tst_file)
  7. getRelativePath(File root, File file)
  8. getRelativePath(File root, File file)
  9. getRelativePath(File root, File target, String fileSeparator)