简体   繁体   中英

how to limit the depth of a recursive file listing in JAVA?

Is there a way to limit the depth of a recursive file listing in Java? I'm using FileUtils.listFiles(File directory, String[] extensions, boolean recursive) of Apache commons-io to list files of a specified directory, but this API return all items of this directory.

A simple Google found this

/**
 * Construct an instance with a directory and a file filter and an optional
 * limit on the <i>depth</i> navigated to.
 * <p>
 * The filters control which files and directories will be navigated to as part
 * of the walk. This constructor uses {@link FileFilterUtils#makeDirectoryOnly(IOFileFilter)}
 * and {@link FileFilterUtils#makeFileOnly(IOFileFilter)} internally to combine the filters.
 * A <code>null</code> filter means that no filtering should occur.
 *
 * @param directoryFilter  the filter to apply to directories, null means visit all directories
 * @param fileFilter  the filter to apply to files, null means visit all files
 * @param depthLimit  controls how <i>deep</i> the hierarchy is
 *  navigated to (less than 0 means unlimited)
 */
protected DirectoryWalker(IOFileFilter directoryFilter, IOFileFilter fileFilter, int depthLimit) {
    if (directoryFilter == null && fileFilter == null) {
        this.filter = null;
    } else {
        directoryFilter = (directoryFilter != null ? directoryFilter : TrueFileFilter.TRUE);
        fileFilter = (fileFilter != null ? fileFilter : TrueFileFilter.TRUE);
        directoryFilter = FileFilterUtils.makeDirectoryOnly(directoryFilter);
        fileFilter = FileFilterUtils.makeFileOnly(fileFilter);
        this.filter = FileFilterUtils.or(directoryFilter, fileFilter);
    }
    this.depthLimit = depthLimit;
}

So I guess that you need to set the depthLimit variable,

Ref: http://www.programcreek.com/java-api-examples/index.php?api=org.apache.commons.io.filefilter.TrueFileFilter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM