Search through the directory tree in Java

Description

The following code shows how to search through the directory tree.

Example


/*from  w  w  w .  j av  a  2  s  .c  om*/
/* 
 * 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
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

import java.io.File;

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

public final class Main {

  /**
   * 
   * 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 java.io.File 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;
  }

}




















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip