Java Path Relative getRelativeName(File file, File root)

Here you can find the source of getRelativeName(File file, File root)

Description

Strips off the part of the path before the start of the root file.

License

Apache License

Parameter

Parameter Description
file a parameter
root a parameter

Declaration

public static String getRelativeName(File file, File root) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.File;

public class Main {
    /**/*from w w  w  .  j a  v  a2  s  .  com*/
     * Strips off the part of the path before the start of the root file. If the root is c:\temp\foo
     * and the file is c:\temp\foo\folder\file.txt this will return folder\file.txt
     * 
     * @param file
     * @param root
     * @return
     */
    public static String getRelativeName(File file, File root) {
        int length = root.getAbsolutePath().length();
        String absolutePath = file.getAbsolutePath();
        String relativePath;

        if (absolutePath.length() == length) {
            if (file.getAbsolutePath().equals(root.getAbsolutePath())) {
                // They are the same file
                relativePath = "";
            } else {
                throw new RuntimeException(
                        String.format("Something looks wrong with the parameters : file [%s] and root [%s]",
                                file.getAbsolutePath(), root.getAbsolutePath()));
            }
        } else {
            relativePath = absolutePath.substring(length + 1, absolutePath.length());
        }
        return relativePath;
    }
}

Related

  1. getRelativeFileName(String filePath, String directoryPath)
  2. getRelativeFilePath(File absolutePath, File reference)
  3. getRelativeFilePath(String filePath, String relativePathPrefix)
  4. getRelativeLastModifiedTimeFile()
  5. getRelativeLink(File target, File base)
  6. getRelativeName(final File directory, final File file)
  7. getRelativeName(final File file)
  8. getRelativeParentDirectory(File base, File file)
  9. getRelativeTemporaryFilename(String directory, String suffix, boolean autodelete)