Java Path Relative Get getRelativePath(String filePath, String basePath)

Here you can find the source of getRelativePath(String filePath, String basePath)

Description

get Relative Path

License

Open Source License

Declaration

public static String getRelativePath(String filePath, String basePath) 

Method Source Code

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

import java.io.File;

import java.io.IOException;

import java.util.regex.Pattern;

public class Main {

    public static String getRelativePath(String filePath, String basePath) {
        File target = new File(filePath);
        File base = new File(basePath);
        StringBuilder result = new StringBuilder();

        try {//from   www.  j a  v a 2s  .c om
            String[] baseComponents = base.getCanonicalPath().split(Pattern.quote(File.separator));
            String[] targetComponents = target.getCanonicalPath().split(Pattern.quote(File.separator));

            // skip common components
            int index = 0;
            for (; index < targetComponents.length && index < baseComponents.length; ++index) {
                if (!targetComponents[index].equals(baseComponents[index])) {
                    break;
                }
            }
            if (index != baseComponents.length) {
                // backtrack to base directory
                for (int i = index; i < baseComponents.length; ++i) {
                    result.append("..");
                    result.append(File.separator);
                }
            }
            for (; index < targetComponents.length; ++index) {
                result.append(targetComponents[index]);
                result.append(File.separator);
            }
            if (!target.getPath().endsWith("/") && !target.getPath().endsWith("\\")) {
                // remove final path separator
                result.delete(result.length() - "/".length(), result.length());
            }
        } catch (IOException e) {
            result.append(filePath);
        }
        return result.toString();
    }
}

Related

  1. getRelativePath(String base, String relative, boolean isBaseFile)
  2. getRelativePath(String baseFullPath, File file)
  3. getRelativePath(String basePath, String path)
  4. getRelativePath(String basePath, String pathToRelativize)
  5. getRelativePath(String fileName, String projFile)
  6. getRelativePath(String from, String to)
  7. getRelativePath(String parent, String child)
  8. getRelativePath(String path, String base)
  9. getRelativePath(String root, String path)