Java File Find find(final File fileDir, final String fileNameRegex)

Here you can find the source of find(final File fileDir, final String fileNameRegex)

Description

Find a file in a given directory with the specified regex pattern.

License

CDDL license

Parameter

Parameter Description
fileDir the directory to search
fileNameRegex the (Java String matches compatible) regex pattern

Exception

Parameter Description
RuntimeException if more than one match was found

Return

the file if found, or null if not found

Declaration

public static File find(final File fileDir, final String fileNameRegex) 

Method Source Code


//package com.java2s;
/*/*from w  ww .  j  a  v  a2s  .c o  m*/
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions copyright [year] [name of copyright owner]".
 *
 * Copyright 2014 ForgeRock AS.
 */

import java.io.File;

import java.io.FilenameFilter;

public class Main {
    /**
     * Find a file in a given directory with the specified regex pattern.
     *
     * @param fileDir the directory to search
     * @param fileNameRegex the (Java String matches compatible) regex pattern
     * @return the file if found, or null if not found
     * @throws RuntimeException if more than one match was found
     */
    public static File find(final File fileDir, final String fileNameRegex) {
        File[] found = fileDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.matches(fileNameRegex);
            }
        });
        if (found != null && found.length != 0) {
            if (found.length == 1) {
                return found[0];
            } else {
                // TODO better exception
                throw new RuntimeException(
                        "More than one matching file found in " + fileDir + " for " + fileNameRegex);
            }
        } else {
            return null;
        }
    }
}

Related

  1. find(File file)
  2. find(File file, Pattern pattern, int limit, List found, Set visited)
  3. find(File folder, final String name)
  4. find(File path, Boolean recursive)
  5. find(File root)
  6. find(final File root, final String name)
  7. find(String _sSourceString, String _sReg, int group)
  8. find(String executable, File... dirs)
  9. find(String name, File dir)