Java Path Relative Get getRelativePath(File target, File relativeTo)

Here you can find the source of getRelativePath(File target, File relativeTo)

Description

get Relative Path

License

Apache License

Declaration

public static String getRelativePath(File target, File relativeTo) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static String getRelativePath(File target, File relativeTo) {
        List<File> targetPaths = new ArrayList<File>();
        List<File> relativePaths = new ArrayList<File>();

        generateList(target, targetPaths);
        generateList(relativeTo, relativePaths);

        String result = "";

        List<File> namedPaths = new ArrayList<File>();
        namedPaths.addAll(targetPaths);//from   w  w w  .  ja va  2 s.  c  o m
        namedPaths.removeAll(relativePaths);
        for (int ctr = 0; ctr < namedPaths.size(); ctr++) {
            result = namedPaths.get(ctr).getName() + "/" + result;
        }
        result = result.substring(0, result.length() - 1);

        List<File> levels = new ArrayList<File>();
        levels.addAll(relativePaths);
        levels.removeAll(targetPaths);
        for (int ctr = 0; ctr < levels.size() - 1; ctr++) {
            result = "../" + result;
        }

        return result;
    }

    private static void generateList(File currentFile, List<File> targetPaths) {
        while (currentFile != null) {
            targetPaths.add(currentFile);
            currentFile = currentFile.getParentFile();
        }
    }
}

Related

  1. getRelativePath(File source, File destination)
  2. getRelativePath(File source, File target)
  3. getRelativePath(File src, File dst)
  4. getRelativePath(File subj, File relativeTo)
  5. getRelativePath(File target, File base)
  6. getRelativePath(File wd, File file)
  7. getRelativePath(final File base, final File child)
  8. getRelativePath(final File base, final File name)
  9. getRelativePath(final File baseDirectory, final File f)