在Java

时间:2019-03-05 03:57:21

标签: java

我想知道在目录中搜索文件及其子目录的更快方法。但是,我知道父目录,但不知道祖父母目录。 例如c:/ temp / test / * / 111 / abx.txt

我尝试了File.walkFileTree,但由于无法使用而不确定如何使用它。

请帮助。 谢谢

2 个答案:

答案 0 :(得分:0)

您可以结合使用Files类和Stream API来完成此任务,如下所示:

Files.walk(Paths.get(path))
    .filter(Files::isRegularFile)
    .forEach(System.out::println);

答案 1 :(得分:0)

下面是一个示例,向您展示如何从目录“ / Users / mkyong / websites”及其所有子目录中搜索名为“ post.php”的文件。

import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileSearch {
private String fileNameToSearch;
private List<String> result = new ArrayList<String>();

public String getFileNameToSearch() {
    return fileNameToSearch;
}

public void setFileNameToSearch(String fileNameToSearch) {
    this.fileNameToSearch = fileNameToSearch;
}

public List<String> getResult() {
    return result;
}

public static void main(String[] args) {

    FileSearch fileSearch = new FileSearch();

    // try different directory and filename :)
    fileSearch.searchDirectory(new File("/Users/mkyong/websites"), "post.php");

    int count = fileSearch.getResult().size();
    if (count == 0) {
        System.out.println("\nNo result found!");
    } else {
        System.out.println("\nFound " + count + " result!\n");
        for (String matched : fileSearch.getResult()) {
            System.out.println("Found : " + matched);
        }
    }
}

public void searchDirectory(File directory, String fileNameToSearch) {
    setFileNameToSearch(fileNameToSearch);

    if (directory.isDirectory()) {
        search(directory);
    } else {
        System.out.println(directory.getAbsoluteFile() + " is not a directory!");
    }

}

private void search(File file) {
    if (file.isDirectory()) {
        System.out.println("Searching directory ... " + file.getAbsoluteFile());

        // do you have permission to read this directory?
        if (file.canRead()) {
            for (File temp : file.listFiles()) {
                if (temp.isDirectory()) {
                    search(temp);
                } else {
                    if (getFileNameToSearch().equals(temp.getName().toLowerCase())) {
                        result.add(temp.getAbsoluteFile().toString());
                    }

                }
            }

        } else {
            System.out.println(file.getAbsoluteFile() + "Permission Denied");
        }
    }

}

}