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

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

Description

Returns the relative path of file to the file basedir.

License

Open Source License

Parameter

Parameter Description
baseDir the base directory or file.
file the file.

Exception

Parameter Description
IOException in case of an I/O error.

Return

the relative path of the file to the basedir.

Declaration

public static String getRelativePath(File baseDir, File file) throws IOException 

Method Source Code


//package com.java2s;
import java.io.File;

import java.io.IOException;

public class Main {
    /**// w w  w  .java 2 s.co m
     * Returns the relative path of <code>file</code> to the file
     * <code>basedir</code>.
     * @param baseDir the base directory or file.
     * @param file the file.
     * @return the relative path of the file to the basedir.
     * @throws IOException in case of an I/O error.
     */
    public static String getRelativePath(File baseDir, File file) throws IOException {
        final String base = baseDir.getCanonicalPath();
        String fileName = file.getCanonicalPath();

        if (fileName.startsWith(base)) {
            fileName = fileName.substring(base.length());
            if (fileName.charAt(0) == '/') {
                fileName = fileName.substring(1);
            }
        } else {
            throw new RuntimeException("Cannot add file '" + file + "' with different baseDir '" + baseDir + "'.");
        }
        return fileName;
    }
}

Related

  1. getRelativePath(File base, File name)
  2. getRelativePath(File base, File path)
  3. getRelativePath(File base, File path)
  4. getRelativePath(File base, File target)
  5. getRelativePath(File baseDir, File file)
  6. getRelativePath(File baseDir, File file)
  7. getRelativePath(File baseDir, File file)
  8. getRelativePath(File baseDir, File subFile, String seperator)
  9. getRelativePath(File baseFile, File file)