Searches through the directory tree : Directory « File Input Output « Java

Searches through the directory tree

 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.


 * FileUtils is a collection of routines for common file system operations.
 * @author Dan Jemiolo (danj)

public final class FileUtils {

   * This is a convenience method that calls find(File, String, boolean) with
   * the last parameter set to "false" (does not match directories).
   * @see #find(File, String, boolean)
  public static File find(File contextRoot, String fileName) {
    return find(contextRoot, fileName, false);

   * Searches through the directory tree under the given context directory and
   * finds the first file that matches the file name. If the third parameter is
   * true, the method will also try to match directories, not just "regular"
   * files.
   * @param contextRoot
   *          The directory to start the search from.
   * @param fileName
   *          The name of the file (or directory) to search for.
   * @param matchDirectories
   *          True if the method should try and match the name against directory
   *          names, not just file names.
   * @return The representing the <em>first</em> file or
   *         directory with the given name, or null if it was not found.
  public static File find(File contextRoot, String fileName, boolean matchDirectories) {
    if (contextRoot == null)
      throw new NullPointerException("NullContextRoot");

    if (fileName == null)
      throw new NullPointerException("NullFileName");

    if (!contextRoot.isDirectory()) {
      Object[] filler = { contextRoot.getAbsolutePath() };
      String message = "NotDirectory";
      throw new IllegalArgumentException(message);

    File[] files = contextRoot.listFiles();

    // for all children of the current directory...
    for (int n = 0; n < files.length; ++n) {
      String nextName = files[n].getName();

      // if we find a directory, there are two possibilities:
      // 1. the names match, AND we are told to match directories.
      // in this case we're done
      // 2. not told to match directories, so recurse
      if (files[n].isDirectory()) {
        if (nextName.equals(fileName) && matchDirectories)
          return files[n];

        File match = find(files[n], fileName);

        if (match != null)
          return match;

      // in the case of regular files, just check the names
      else if (nextName.equals(fileName))
        return files[n];

    return null;



Related examples in the same category

1.Create directory
2.Create directory along with required nonexistent parent directories
3.Create directory tree (nested/cascade folders)
4.Create a directories recursively
5.Copying a Directory: Copies files under srcDir to dstDir, if dstDir does not exist, it will be created.
6.Delete a non-empty directory: Deletes all files and subdirectories under dir.
7.Listing the Files or Subdirectories in a Directory
8.Listing the File System Roots
9.The Directory Listing ApplicationThe Directory Listing Application
10.use list( ) to examine the contents of a directory:
11.Reading and Printing a Directory HierarchyReading and Printing a Directory Hierarchy
12.Display a file system in a JTree viewDisplay a file system in a JTree view
13.File Tree DemoFile Tree Demo
14.File Table HTMLFile Table HTML
15.A standalone program that deletes a specified file or directory
16.Get Last modification time of a file or directory
17.Set last modified time of a file or directory
18.List contents of a directory
19.Determine if file or directory exists
20.Determine if File or Directory is hidden
21.Check if a directory is not empty
22.Get name of parent directory
23.Get name of specified file or directory
24.Get current directory
25.Mark file or directory Read Only
26.Rename file or directory
27.Traversing all files and directories under dir
28.Traversing only directories under dir
29.Traversing only files under dir
30.Creates and displays a window containing a list of files and sub-directories in a specified directory
31.Calculate directory size
32.Delete directory recursively
33.Determining If Two Filename Paths Refer to the Same File
34.Recursive directory deletion
35.Recursivly delete directory
36.Starts at the directory given and tests to see whether it is empty
37.Directory Walker
38.Utility methods for handling files and directories
39.Creates a new and empty directory in the default temp directory using the given prefix.
40.Count files in a directory (including files in all subdirectories)
41.Create a unique directory within a directory 'root'
42.Creates a new empty temporary directory.
43.Get Files Recurse
44.Recursively search a directory tree
45.Find directoriesFind directories