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


当前回答

一个注释根据获得目录中的所有文件。 方法files .walk(path)将通过遍历以给定起始文件为根的文件树来返回所有文件。

例如,下面有一个文件树:

\---folder
    |   file1.txt
    |   file2.txt
    |
    \---subfolder
            file3.txt
            file4.txt

使用java.nio.file.Files.walk(路径):

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

给出如下结果:

folder\file1.txt
folder\file2.txt
folder\subfolder\file3.txt
folder\subfolder\file4.txt

要获取当前目录下的所有文件,请使用java.nio.file.Files.list(Path):

Files.list(Paths.get("folder"))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);

结果:

folder\file1.txt
folder\file2.txt

其他回答

import java.io.File;


public class ReadFilesFromFolder {
  public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
  static String temp = "";

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
    listFilesForFolder(folder);
  }

  public static void listFilesForFolder(final File folder) {

    for (final File fileEntry : folder.listFiles()) {
      if (fileEntry.isDirectory()) {
        // System.out.println("Reading files under the folder "+folder.getAbsolutePath());
        listFilesForFolder(fileEntry);
      } else {
        if (fileEntry.isFile()) {
          temp = fileEntry.getName();
          if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt"))
            System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
        }

      }
    }
  }
}

java.io.FileFilter的用法很好,见https://stackoverflow.com/a/286001/146745

File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {          
    public boolean accept(File file) {
        return file.isFile();
    }
});

关于这个主题的所有使用Java 8新函数的答案都忽略了关闭流。接受的答案中的例子应该是:

try (Stream<Path> filePathStream=Files.walk(Paths.get("/home/you/Desktop"))) {
    filePathStream.forEach(filePath -> {
        if (Files.isRegularFile(filePath)) {
            System.out.println(filePath);
        }
    });
}

从文件的javadoc。走路的方法:

返回的流封装了一个或多个directorystream。如果 需要及时处理文件系统资源 应该使用Try-with-resources构造来确保 流的close方法在流操作完成后调用。

File directory = new File("/user/folder");      
File[] myarray;  
myarray=new File[10];
myarray=directory.listFiles();
for (int j = 0; j < myarray.length; j++)
{
       File path=myarray[j];
       FileReader fr = new FileReader(path);
       BufferedReader br = new BufferedReader(fr);
       String s = "";
       while (br.ready()) {
          s += br.readLine() + "\n";
       }
}
private static final String ROOT_FILE_PATH="/";
File f=new File(ROOT_FILE_PATH);
File[] allSubFiles=f.listFiles();
for (File file : allSubFiles) {
    if(file.isDirectory())
    {
        System.out.println(file.getAbsolutePath()+" is directory");
        //Steps for directory
    }
    else
    {
        System.out.println(file.getAbsolutePath()+" is file");
        //steps for files
    }
}