Test if a file lives under the given directory, either as a direct child or a distant grandchild. - Android java.io

Android examples for java.io:File Directory

Description

Test if a file lives under the given directory, either as a direct child or a distant grandchild.

Demo Code

import java.io.File;

public class Main {

  /**/*from  w  w w  .j  a  v  a  2s.co  m*/
   * Test if a file lives under the given directory, either as a direct child or a
   * distant grandchild.
   * <p>
   * Both files <em>must</em> have been resolved using
   * {@link File#getCanonicalFile()} to avoid symlink or path traversal attacks.
   */
  public static boolean contains(File[] dirs, File file) {
    for (File dir : dirs) {
      if (contains(dir, file)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Test if a file lives under the given directory, either as a direct child or a
   * distant grandchild.
   * <p>
   * Both files <em>must</em> have been resolved using
   * {@link File#getCanonicalFile()} to avoid symlink or path traversal attacks.
   */
  public static boolean contains(File dir, File file) {
    if (dir == null || file == null)
      return false;

    String dirPath = dir.getAbsolutePath();
    String filePath = file.getAbsolutePath();

    if (dirPath.equals(filePath)) {
      return true;
    }

    if (!dirPath.endsWith("/")) {
      dirPath += "/";
    }
    return filePath.startsWith(dirPath);
  }

}

Related Tutorials