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


当前回答

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

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

其他回答

在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)

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());
            }
        }
    }

}
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class AvoidNullExp {

public static void main(String[] args) {

    List<File> fileList =new ArrayList<>();
     final File folder = new File("g:/master");
     new AvoidNullExp().listFilesForFolder(folder, fileList);
}

    public void listFilesForFolder(final File folder,List<File> fileList) {
        File[] filesInFolder = folder.listFiles();
        if (filesInFolder != null) {
            for (final File fileEntry : filesInFolder) {
                if (fileEntry.isDirectory()) {
                    System.out.println("DIR : "+fileEntry.getName());
                listFilesForFolder(fileEntry,fileList);
            } else {
                System.out.println("FILE : "+fileEntry.getName());
                fileList.add(fileEntry);
            }
         }
        }
     }


}

为了扩展已接受的答案,我将文件名存储到一个数组列表中(而不是仅仅将它们转储到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)。

import java.io.File;


public class Test {

public void test1() {
    System.out.println("TEST 1");
}

public static void main(String[] args) throws SecurityException, ClassNotFoundException{

    File actual = new File("src");
    File list[] = actual.listFiles();
    for(int i=0; i<list.length; i++){
        String substring = list[i].getName().substring(0, list[i].getName().indexOf("."));
        if(list[i].isFile() && list[i].getName().contains(".java")){
                if(Class.forName(substring).getMethods()[0].getName().contains("main")){
                    System.out.println("CLASS NAME "+Class.forName(substring).getName());
                }

         }
    }

}
}

只要传递你的文件夹,它就会告诉你关于方法的主类。