Java Path Relative Get getRelativePath(File original, File directory)

Here you can find the source of getRelativePath(File original, File directory)

Description

Return a relative path to original as seen from given directory.

License

Open Source License

Declaration

public static String getRelativePath(File original, File directory) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

public class Main {
    /**/* w w w  .java2s  .c  o m*/
     * Return a relative path to original as seen from given directory.
     * It may be absolute if they are on different drives on Windows.
     * All file separators will be '/' characters to make the path usable in HTML.
     * e.g. \photos\foo\bar\photo.jpg and \photos\foo\xyz\ => ../bar/photo.jpg
     */
    public static String getRelativePath(File original, File directory) {
        String result = null;
        try {
            String o = original.getCanonicalPath();
            String dir = directory.getCanonicalPath() + File.separator;

            // Find common prefix
            int lastCommon = 0;
            int index = dir.indexOf(File.separator);
            while (index >= 0) {
                if (!dir.regionMatches(true, lastCommon, o, lastCommon, index - lastCommon))
                    break; // No more matching prefix
                lastCommon = index;
                index = dir.indexOf(File.separator, index + 1);
            }

            if (lastCommon == 0) {
                return o; // No common prefix
            }

            StringBuffer resultbuf = new StringBuffer(o.length());
            if (index > 0) {
                // Did not run out of directory path, build relative path
                // while it lasts.
                while (index >= 0) {
                    resultbuf.append("../");
                    index = dir.indexOf(File.separator, index + 1);
                }
            }
            resultbuf.append(o.substring(lastCommon + 1));
            result = resultbuf.toString();
        } catch (Exception e) {
            System.out.println("getRelativePath:" + e);
            result = original.getAbsolutePath();
        }
        return result.replace('\\', '/');
    }
}

Related

  1. getRelativePath(File fromFile, File toFile)
  2. getRelativePath(File fromFolder, File toFile)
  3. getRelativePath(File home, File f)
  4. getRelativePath(File home, File f)
  5. getRelativePath(File home, File f)
  6. getRelativePath(File parent, File child)
  7. getRelativePath(File parent, File child)
  8. getRelativePath(File parent, File f)
  9. getRelativePath(File parentDirectory, File file)