64

可能重复:
使用Java递归列出目录中的所有文件

我如何返回一个包含文件夹上所有文件以及子文件夹的文件数组,我的方法只适用于文件夹,它不包括子文件夹。

public File[] listf(String directoryName) {

    // .............list file
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles();

    for (File file : fList) {
        if (file.isFile()) {
            System.out.println(file.getAbsolutePath());
        } else if (file.isDirectory()) {
            listf(file.getAbsolutePath());
        }
    }
    System.out.println(fList);
    return fList;
}                        
4

3 回答 3

97

使用您当前的代码,进行此调整:

public void listf(String directoryName, List<File> files) {
    File directory = new File(directoryName);

    // Get all files from a directory.
    File[] fList = directory.listFiles();
    if(fList != null)
        for (File file : fList) {      
            if (file.isFile()) {
                files.add(file);
            } else if (file.isDirectory()) {
                listf(file.getAbsolutePath(), files);
            }
        }
}
于 2013-02-03T19:41:40.167 回答
36

使用来自 Apache commons 的 FileUtils

listFiles

public static Collection<File> listFiles(File directory,
                                         String[] extensions,
                                         boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files
于 2013-02-03T19:37:28.473 回答
21

您可以返回 aList而不是数组,事情变得更加简单。

    public static List<File> listf(String directoryName) {
        File directory = new File(directoryName);

        List<File> resultList = new ArrayList<File>();

        // get all the files from a directory
        File[] fList = directory.listFiles();
        resultList.addAll(Arrays.asList(fList));
        for (File file : fList) {
            if (file.isFile()) {
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                resultList.addAll(listf(file.getAbsolutePath()));
            }
        }
        //System.out.println(fList);
        return resultList;
    } 
于 2013-02-03T19:45:23.523 回答