如何通过Java读取文件夹中的所有文件?这与哪个API无关。


当前回答

这将很好地工作:

private static void addfiles(File inputValVal, ArrayList<File> files)
{
  if(inputVal.isDirectory())
  {
    ArrayList <File> path = new ArrayList<File>(Arrays.asList(inputVal.listFiles()));

    for(int i=0; i<path.size(); ++i)
    {
        if(path.get(i).isDirectory())
        {
            addfiles(path.get(i),files);
        }
        if(path.get(i).isFile())
        {
            files.add(path.get(i));
        }
     }

    /*  Optional : if you need to have the counts of all the folders and files you can create 2 global arrays 
        and store the results of the above 2 if loops inside these arrays */
   }

   if(inputVal.isFile())
   {
     files.add(inputVal);
   }

}

其他回答

如果你想要更多的选项,你可以使用这个函数来填充文件夹中文件的数组列表。选项有:递归性和匹配的模式。

public static ArrayList<File> listFilesForFolder(final File folder,
        final boolean recursivity,
        final String patternFileFilter) {

    // Inputs
    boolean filteredFile = false;

    // Ouput
    final ArrayList<File> output = new ArrayList<File> ();

    // Foreach elements
    for (final File fileEntry : folder.listFiles()) {

        // If this element is a directory, do it recursivly
        if (fileEntry.isDirectory()) {
            if (recursivity) {
                output.addAll(listFilesForFolder(fileEntry, recursivity, patternFileFilter));
            }
        }
        else {
            // If there is no pattern, the file is correct
            if (patternFileFilter.length() == 0) {
                filteredFile = true;
            }
            // Otherwise we need to filter by pattern
            else {
                filteredFile = Pattern.matches(patternFileFilter, fileEntry.getName());
            }

            // If the file has a name which match with the pattern, then add it to the list
            if (filteredFile) {
                output.add(fileEntry);
            }
        }
    }

    return output;
}

最佳,安德

在Java 7及更高版本中,您可以使用listdir

Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (Path file: stream) {
        System.out.println(file.getFileName());
    }
} catch (IOException | DirectoryIteratorException x) {
    // IOException can never be thrown by the iteration.
    // In this snippet, it can only be thrown by newDirectoryStream.
    System.err.println(x);
}

您还可以创建一个过滤器,然后将其传递给上面的newDirectoryStream方法

DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
    public boolean accept(Path file) throws IOException {
        try {
            return (Files.isRegularFile(path));
        } catch (IOException x) {
            // Failed to determine if it's a file.
            System.err.println(x);
            return false;
        }
    }
};

有关其他过滤示例,[参见文档]。(http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob)

为了扩展已接受的答案,我将文件名存储到一个数组列表中(而不是仅仅将它们转储到System.out.println),我创建了一个帮助类“MyFileUtils”,这样它就可以被其他项目导入:

class MyFileUtils {
    public static void loadFilesForFolder(final File folder, List<String> fileList){
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                loadFilesForFolder(fileEntry, fileList);
            } else {
                fileList.add( fileEntry.getParent() + File.separator + fileEntry.getName() );
            }
        }
    }
}

我在文件名中添加了完整路径。 你可以这样使用它:

import MyFileUtils;

List<String> fileList = new ArrayList<String>();
final File folder = new File("/home/you/Desktop");
MyFileUtils.loadFilesForFolder(folder, fileList);

// Dump file list values
for (String fileName : fileList){
    System.out.println(fileName);
}

数组列表是通过“value”传递的,但是value是用来指向JVM堆中的同一个数组列表对象的。这样,每次递归调用都将文件名添加到同一个ArrayList中(我们并不是在每次递归调用时创建一个新的ArrayList)。

    static File mainFolder = new File("Folder");
    public static void main(String[] args) {

        lf.getFiles(lf.mainFolder);
    }
    public void getFiles(File f) {
        File files[];
        if (f.isFile()) {
            String name=f.getName();

        } else {
            files = f.listFiles();
            for (int i = 0; i < files.length; i++) {
                getFiles(files[i]);
            }
        }
    }

防止listFiles()函数的nullpointerexception,并递归地从子目录中获取所有文件。

 public void listFilesForFolder(final File folder,List<File> fileList) {
    File[] filesInFolder = folder.listFiles();
    if (filesInFolder != null) {
        for (final File fileEntry : filesInFolder) {
            if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry,fileList);
        } else {
            fileList.add(fileEntry);
        }
     }
    }
 }

 List<File> fileList = new List<File>();
 final File folder = new File("/home/you/Desktop");
 listFilesForFolder(folder);