Java Path Relative Get getRelativePath(final File fromFile, final File toFile)

Here you can find the source of getRelativePath(final File fromFile, final File toFile)

Description

get Relative Path

License

BSD License

Declaration

static String getRelativePath(final File fromFile, final File toFile) 

Method Source Code

//package com.java2s;
/**/* w w w . j  a  v  a  2  s  .  c  o  m*/
 * Copyright (C) 2010-2012 Andrei Pozolotin <Andrei.Pozolotin@gmail.com>
 *
 * All rights reserved. Licensed under the OSI BSD License.
 *
 * http://www.opensource.org/licenses/bsd-license.php
 */

import java.io.File;
import java.io.IOException;

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

public class Main {
    static String getRelativePath(final File fromFile, final File toFile) {

        final String[] fromSegments = getReversePathSegments(fromFile);
        final String[] toSegments = getReversePathSegments(toFile);

        String relativePath = "";
        int i = fromSegments.length - 1;
        int j = toSegments.length - 1;

        // first eliminate common root
        while ((i >= 0) && (j >= 0) && (fromSegments[i].equals(toSegments[j]))) {
            i--;
            j--;
        }

        for (; i >= 0; i--) {
            relativePath += ".." + File.separator;
        }

        for (; j >= 1; j--) {
            relativePath += toSegments[j] + File.separator;
        }

        relativePath += toSegments[j];

        return relativePath;
    }

    static String[] getReversePathSegments(final File file) {
        final List<String> paths = new ArrayList<String>();

        File segment;
        try {
            segment = file.getCanonicalFile();
            while (segment != null) {
                paths.add(segment.getName());
                segment = segment.getParentFile();
            }
        } catch (final IOException e) {
            return null;
        }
        return paths.toArray(new String[paths.size()]);
    }
}

Related

  1. getRelativePath(final File base, final File name)
  2. getRelativePath(final File baseDirectory, final File f)
  3. getRelativePath(final File basePathFile, final File pathFile)
  4. getRelativePath(final File file, final File folder)
  5. getRelativePath(final File from, final File to)
  6. getRelativePath(final File parentDir, final File file)
  7. getRelativePath(final File parentDirectory, final File file)
  8. getRelativePath(final String base, final File targetFile)
  9. getRelativePath(String base, String fullPath)