Here you can find the source of find(File file, Pattern pattern, int limit, List
private static void find(File file, Pattern pattern, int limit, List<File> found, Set<File> visited) throws IOException
//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); } }