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


当前回答

我们可以使用org.apache.commons.io.FileUtils,使用listFiles()方法来读取给定文件夹中的所有文件。

eg:

FileUtils.listFiles(directory, new String[] {"ext1", "ext2"}, true)

这将读取给定目录中具有给定扩展名的所有文件,我们可以在数组中传递多个扩展名,并在文件夹中递归读取(true参数)。

其他回答

防止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);
package com.commandline.folder;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class FolderReadingDemo {
    public static void main(String[] args) {
        String str = args[0];
        final File folder = new File(str);
//      listFilesForFolder(folder);
        listFilesForFolder(str);
    }

    public static void listFilesForFolder(String str) {
        try (Stream<Path> paths = Files.walk(Paths.get(str))) {
            paths.filter(Files::isRegularFile).forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void listFilesForFolder(final File folder) {
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                System.out.println(fileEntry.getName());
            }
        }
    }

}
File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();

for (File file : listOfFiles) {
    if (file.isFile()) {
        System.out.println(file.getName());
    }
}
void getFiles(){
        String dirPath = "E:/folder_name";
        File dir = new File(dirPath);
        String[] files = dir.list();
        if (files.length == 0) {
            System.out.println("The directory is empty");
        } else {
            for (String aFile : files) {
                System.out.println(aFile);
            }
        }
    }

这将读取指定路径下的指定文件扩展名文件(也可以查看子文件夹)

public static Map<String,List<File>> getFileNames(String 
dirName,Map<String,List<File>> filesContainer,final String fileExt){
    String dirPath = dirName;
    List<File>files = new ArrayList<>();
    Map<String,List<File>> completeFiles = filesContainer; 
    if(completeFiles == null) {
        completeFiles = new HashMap<>();
    }
    File file = new File(dirName);

    FileFilter fileFilter = new FileFilter() {
        @Override
        public boolean accept(File file) {
            boolean acceptFile = false;
            if(file.isDirectory()) {
                acceptFile = true;
            }else if (file.getName().toLowerCase().endsWith(fileExt))
              {
                acceptFile = true;
              }
            return acceptFile;
        }
    };
    for(File dirfile : file.listFiles(fileFilter)) {
        if(dirfile.isFile() && 
dirfile.getName().toLowerCase().endsWith(fileExt)) {
            files.add(dirfile);
        }else if(dirfile.isDirectory()) {
            if(!files.isEmpty()) {
                completeFiles.put(dirPath, files);  
            }

getFileNames(dirfile.getAbsolutePath(),completeFiles,fileExt);
        }
    }
    if(!files.isEmpty()) {
        completeFiles.put(dirPath, files);  
    }
    return completeFiles;
}