Java Relative Path Get relativePath(String origin, String target)

Here you can find the source of relativePath(String origin, String target)

Description

relative Path

License

Open Source License

Declaration

public static String relativePath(String origin, String target) 

Method Source Code


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

import java.io.*;

public class Main {
    public static String relativePath(String origin, String target) {
        try {//from w  ww. j  a v  a2  s. c  o m
            origin = (new File(origin)).getCanonicalPath();
            File targetFile = new File(target);
            if (targetFile.isAbsolute())
                target = targetFile.getCanonicalPath();
            else
                target = (new File(origin, target)).getCanonicalPath();
        } catch (IOException e) {
            return null;
        }

        if (origin.equals(target)) {
            // origin and target is identical.
            return ".";
        }

        if (origin.equals(File.separator)) {
            // origin is root.
            return "." + target;
        }

        String prefix = "";
        String root = File.separator;

        if (System.getProperty("os.name").indexOf("Windows") != -1) {
            if (origin.startsWith("\\\\") || target.startsWith("\\\\")) {
                // Windows UNC path not supported.
                return null;
            }

            char originLetter = origin.charAt(0);
            char targetLetter = target.charAt(0);
            if (Character.isLetter(originLetter) && Character.isLetter(targetLetter)) {
                // Windows only
                if (originLetter != targetLetter) {
                    // Drive letters differ
                    return null;
                }
            }

            prefix = "" + originLetter + ':';
            root = prefix + File.separator;
        }

        String relative = "";
        while (!target.startsWith(origin + File.separator)) {
            origin = (new File(origin)).getParent();
            if (origin.equals(root))
                origin = prefix;
            relative += "..";
            relative += File.separator;
        }

        return relative + target.substring(origin.length() + 1);
    }
}

Related

  1. relativePath(File path, File relativeTo)
  2. relativePath(File root, File node)
  3. relativePath(File src, File dest)
  4. relativePath(final File root, final File file)
  5. relativePath(final String inputPath, final File file)
  6. relativePath(String p_absolutePath, String p_currentPath)
  7. relativePathFiles(String relativePath, final String... fileNamesRegex)
  8. relativeTo(File peer, String filename)
  9. relativeToAbsoluteFilePath(String s)