Java Relative Path Get relativePath(File from, File to)

Here you can find the source of relativePath(File from, File to)

Description

relative Path

License

Open Source License

Declaration

static public String relativePath(File from, File to) 

Method Source Code


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

import java.io.File;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Main {
    static public String relativePath(File from, File to) {
        return relativePath(from, to, File.separatorChar);
    }/*from  w  ww.  j  av  a2  s . c  o  m*/

    static public String relativePath(File from, File to, char separatorChar) {
        String fromPath = from.getAbsolutePath();
        String toPath = to.getAbsolutePath();
        boolean isDirectory = from.isDirectory();
        return relativePath(fromPath, toPath, isDirectory, separatorChar);
    }

    public static String relativePath(String fromPath, String toPath, boolean fromIsDirectory, char separatorChar) {
        ArrayList<String> fromElements = splitPath(fromPath);
        ArrayList<String> toElements = splitPath(toPath);
        while (!fromElements.isEmpty() && !toElements.isEmpty()) {
            if (!(fromElements.get(0).equals(toElements.get(0)))) {
                break;
            }
            fromElements.remove(0);
            toElements.remove(0);
        }

        StringBuffer result = new StringBuffer();
        for (int i = 0; i < fromElements.size() - (fromIsDirectory ? 0 : 1); i++) {
            result.append("..");
            result.append(separatorChar);
        }
        for (String s : toElements) {
            result.append(s);
            result.append(separatorChar);
        }
        return result.substring(0, result.length() - 1);
    }

    private static ArrayList<String> splitPath(String path) {
        ArrayList<String> pathElements = new ArrayList<String>();
        for (StringTokenizer st = new StringTokenizer(path, File.separator); st.hasMoreTokens();) {
            String token = st.nextToken();
            if (token.equals(".")) {
                // do nothing
            } else if (token.equals("..")) {
                if (!pathElements.isEmpty()) {
                    pathElements.remove(pathElements.size() - 1);
                }
            } else {
                pathElements.add(token);
            }
        }
        return pathElements;
    }
}

Related

  1. relativePath(File baseDir, File child)
  2. relativePath(File baseDir, File storeFile)
  3. relativePath(File baseDir, File storeFile)
  4. relativePath(File descendant, File root)
  5. relativePath(File file, String path)
  6. relativePath(File home, File f)
  7. relativePath(File IncludedFile, File UpperDirectory)
  8. relativePath(File parent, File child)
  9. relativePath(File parent, File child)