【问题标题】:how to limit the depth of a recursive file listing in JAVA?如何限制 JAVA 中递归文件列表的深度?
【发布时间】:2016-04-18 05:30:01
【问题描述】:

有没有办法限制 Java 中递归文件列表的深度? 我正在使用 Apache commons-io 的 FileUtils.listFiles(File directory, String[] extensions, boolean recursive) 来列出指定目录的文件,但是这个 API 返回了这个目录的所有项目。

【问题讨论】:

标签: java file-listing


【解决方案1】:

一个简单的谷歌发现了这个

/**
 * 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;
}

所以我猜你需要设置 depthLimit 变量,

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

【讨论】:

    猜你喜欢
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 2012-10-26
    • 2016-03-02
    • 2011-02-07
    • 1970-01-01
    相关资源
    最近更新 更多