Java Path Relative Get getRelativePath(File dir, File file)

Here you can find the source of getRelativePath(File dir, File file)

Description

get Relative Path

License

LGPL

Declaration

public static String getRelativePath(File dir, File file) 

Method Source Code


//package com.java2s;
/*//from  ww  w .j  a v  a2s . c  o  m
 GNU LESSER GENERAL PUBLIC LICENSE
 Version 3, 29 June 2007
    
 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.
    
    
 This version of the GNU Lesser General Public License incorporates
 the terms and conditions of version 3 of the GNU General Public
 License
 */

import java.io.File;

public class Main {
    public static String getRelativePath(File dir, File file) {

        if (dir == null || file == null) {
            throw new IllegalArgumentException("dir and file arguments must not be null");
        }

        String dirname = dir.toURI().normalize().toString();
        String filename = file.toURI().normalize().toString();

        // file is not under dir
        if (filename.length() < dirname.length() || !filename.startsWith(dirname)) {
            return null;
        }

        // file == dir
        if (filename.length() == dirname.length()) {
            return "";
        }

        // file is under dir
        return filename.substring(dirname.length());
    }
}

Related

  1. getRelativePath(File baseFile, File file)
  2. getRelativePath(File baseFolder, File subject)
  3. getRelativePath(File child, File directory)
  4. getRelativePath(File currentDir, File target)
  5. getRelativePath(File dir, File child)
  6. getRelativePath(File f, File base)
  7. getRelativePath(File file)
  8. getRelativePath(File file, File basedir)
  9. getRelativePath(File file, File baseDir)