Java Relative Path Get relativePath(File src, File dest)

Here you can find the source of relativePath(File src, File dest)

Description

relative Path

License

Apache License

Declaration

public static String relativePath(File src, File dest) 

Method Source Code

//package com.java2s;
/*#######################################################
 *
 *   Maintained by Gregor Santner, 2017-
 *   https://gsantner.net//*from   w w w. j a v a2  s  .c o m*/
 *
 *   License: Apache 2.0
 *  https://github.com/gsantner/opoc/#licensing
 *  https://www.apache.org/licenses/LICENSE-2.0
 *
#########################################################*/

import java.io.File;

import java.io.IOException;

import java.util.regex.Pattern;

public class Main {
    public static String relativePath(File src, File dest) {
        try {
            String[] srcSplit = (src.isDirectory() ? src : src.getParentFile()).getCanonicalPath()
                    .split(Pattern.quote(File.separator));
            String[] destSplit = dest.getCanonicalPath().split(Pattern.quote(File.separator));
            StringBuilder sb = new StringBuilder();
            int i = 0;

            for (; i < destSplit.length && i < srcSplit.length; ++i) {
                if (!destSplit[i].equals(srcSplit[i]))
                    break;
            }
            if (i != srcSplit.length) {
                for (int iUpperDir = i; iUpperDir < srcSplit.length; ++iUpperDir) {
                    sb.append("..");
                    sb.append(File.separator);
                }
            }
            for (; i < destSplit.length; ++i) {
                sb.append(destSplit[i]);
                sb.append(File.separator);
            }
            if (!dest.getPath().endsWith("/") && !dest.getPath().endsWith("\\")) {
                sb.delete(sb.length() - File.separator.length(), sb.length());
            }
            return sb.toString();
        } catch (IOException | NullPointerException exception) {
            return null;
        }
    }
}

Related

  1. relativePath(File IncludedFile, File UpperDirectory)
  2. relativePath(File parent, File child)
  3. relativePath(File parent, File child)
  4. relativePath(File path, File relativeTo)
  5. relativePath(File root, File node)
  6. relativePath(final File root, final File file)
  7. relativePath(final String inputPath, final File file)
  8. relativePath(String origin, String target)
  9. relativePath(String p_absolutePath, String p_currentPath)