Java Path Relative Get getRelativePath(File root, File target, String fileSeparator)

Here you can find the source of getRelativePath(File root, File target, String fileSeparator)

Description

get Relative Path

License

Open Source License

Declaration

public static String getRelativePath(File root, File target, String fileSeparator) 

Method Source Code


//package com.java2s;
/*//from w w w. j ava 2 s. c  o  m
 * This file is part of the Jose Project
 * see http://jose-chess.sourceforge.net/
 * (c) 2002-2006 Peter Sch?fer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 */

import java.io.*;

import java.util.Vector;

public class Main {
    public static String getRelativePath(File root, File target, String fileSeparator) {
        if (fileSeparator == null)
            fileSeparator = File.separator;

        Vector rootHierarchy = new Vector();
        for (File dir = root; dir != null; dir = dir.getParentFile())
            rootHierarchy.add(dir);

        StringBuffer buf = new StringBuffer();
        for (; target != null; target = target.getParentFile()) {
            int idx = rootHierarchy.indexOf(target);
            if (idx == 0) {
                //  root is a direct parent of target
                if (buf.length() == 0)
                    buf.append(".");
                break;
            } else if (idx > 0) {
                //  there is a common parent
                while (idx-- > 0) {
                    if (buf.length() > 0)
                        buf.insert(0, fileSeparator);
                    buf.insert(0, "..");
                }
                break;
            } else {
                //  climb one up
                if (buf.length() > 0)
                    buf.insert(0, fileSeparator);
                buf.insert(0, target.getName());
            }
        }
        return buf.toString();
    }
}

Related

  1. getRelativePath(File path, File base)
  2. getRelativePath(File path, File basePath)
  3. getRelativePath(File ref_file, File tst_file)
  4. getRelativePath(File root, File file)
  5. getRelativePath(File root, File file)
  6. getRelativePath(File rootDirectory, File file)
  7. getRelativePath(File source, File destination)
  8. getRelativePath(File source, File target)
  9. getRelativePath(File src, File dst)