Java File Find find(File file, Pattern pattern, int limit, List found, Set visited)

Here you can find the source of find(File file, Pattern pattern, int limit, List found, Set visited)

Description

find

License

Open Source License

Declaration

private static void find(File file, Pattern pattern, int limit, List<File> found, Set<File> visited)
            throws IOException 

Method Source Code

//package com.java2s;
/**/*from   w  w  w. ja  v a2  s  . c  o m*/
 * Copyright (c) 2013 Puppet Labs, Inc. and other contributors, as listed below.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *   Puppet Labs
 */

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;
import java.util.Arrays;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static void find(File file, Pattern pattern, int limit, List<File> found, Set<File> visited)
            throws IOException {
        if (visited.contains(file))
            throw new IOException("Circular file structure detected");

        visited.add(file);

        if (limit > -1 && found.size() >= limit)
            return;

        if (file.isDirectory()) {
            File[] subFiles = file.listFiles();
            Arrays.sort(subFiles);
            for (File subFile : subFiles) {
                find(subFile, pattern, limit, found, visited);
            }
        } else {
            Matcher m = pattern.matcher(file.getName());
            if (m.matches())
                found.add(file);
        }
    }

    public static File[] find(File file, String pattern) throws IOException {
        return find(file, pattern, -1);
    }

    public static File[] find(File file, String pattern, int limit) throws IOException {
        Set<File> visited = new HashSet<File>();
        Pattern compiledPattern = Pattern.compile(pattern);
        List<File> found = new ArrayList<File>();
        find(file, compiledPattern, limit, found, visited);

        return found.toArray(new File[found.size()]);
    }

    public static File[] find(String root, String pattern) throws IOException {
        return find(new File(root), pattern, -1);
    }

    public static File[] find(String root, String pattern, int limit) throws IOException {
        return find(new File(root), pattern, limit);
    }
}

Related

  1. find(File absolutePath, FileFilter filter)
  2. find(File baseFile, String regex)
  3. find(File dir, String baseName)
  4. find(File dir, String suffix, Set ignore)
  5. find(File file)
  6. find(File folder, final String name)
  7. find(File path, Boolean recursive)
  8. find(File root)
  9. find(final File fileDir, final String fileNameRegex)