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

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

Description

Given a file and base directory, the method returns file path relative to base directory.

License

Open Source License

Declaration

public static String getRelativePath(File file, File baseDirectory) throws Exception 

Method Source Code

//package com.java2s;

import java.io.File;

public class Main {
    /**//from  w ww. j  av a2s  .c om
     * Given a file and base directory, the method returns file path relative to
     * base directory. If file is not under base directory, the method throws
     * IllegalArgumentException
     */
    public static String getRelativePath(File file, File baseDirectory) throws Exception {
        String baseDirAsString = baseDirectory.getCanonicalPath();
        String filePathAsString = file.getCanonicalPath();
        int dirIndex = filePathAsString.indexOf(baseDirAsString);
        if (dirIndex == -1) {
            throw new IllegalArgumentException("Directory path is not part of file path. directory = "
                    + baseDirAsString + " scenario path = " + filePathAsString);
        }
        return filePathAsString.substring(dirIndex + baseDirAsString.length() + 1);
    }
}

Related

  1. getRelativePath(File dir, File file)
  2. getRelativePath(File f, File base)
  3. getRelativePath(File file)
  4. getRelativePath(File file, File basedir)
  5. getRelativePath(File file, File baseDir)
  6. getRelativePath(File file, File directory)
  7. getRelativePath(File file, File folder)
  8. getRelativePath(File file, File root)
  9. getRelativePath(File file, File root)