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


当前回答

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

其他回答

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

for (File file : listOfFiles) {
    if (file.isFile()) {
        System.out.println(file.getName());
    }
}
package com;


import java.io.File;

/**
 *
 * @author ?Mukesh
 */
public class ListFiles {

     static File mainFolder = new File("D:\\Movies");

     public static void main(String[] args)
     {
         ListFiles lf = new ListFiles();
         lf.getFiles(lf.mainFolder);

         long fileSize = mainFolder.length();
             System.out.println("mainFolder size in bytes is: " + fileSize);
             System.out.println("File size in KB is : " + (double)fileSize/1024);
             System.out.println("File size in MB is :" + (double)fileSize/(1024*1024));
     }
     public void getFiles(File f){
         File files[];
         if(f.isFile())
             System.out.println(f.getAbsolutePath());
         else{
             files = f.listFiles();
             for (int i = 0; i < files.length; i++) {
                 getFiles(files[i]);
             }
         }
     }
}
public static List<File> files(String dirname) {
    if (dirname == null) {
        return Collections.emptyList();
    }

    File dir = new File(dirname);
    if (!dir.exists()) {
        return Collections.emptyList();
    }

    if (!dir.isDirectory()) {
        return Collections.singletonList(file(dirname));
    }

    return Arrays.stream(Objects.requireNonNull(dir.listFiles()))
        .collect(Collectors.toList());
}

您可以将文件路径设置为参数,并创建包含所有文件路径的列表,而不必手动将其放入列表中。然后使用for循环和读取器。txt文件示例:

public static void main(String[] args) throws IOException{    
File[] files = new File(args[0].replace("\\", "\\\\")).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".txt"); } });
    ArrayList<String> filedir = new ArrayList<String>();
    String FILE_TEST = null;
    for (i=0; i<files.length; i++){
            filedir.add(files[i].toString());
            CSV_FILE_TEST=filedir.get(i) 

        try(Reader testreader = Files.newBufferedReader(Paths.get(FILE_TEST));
            ){
              //write your stuff
                 }}}

使用Java 1.7来递归列出命令行指定目录中的文件的简单示例:

import java.io.File;

public class List {
    public static void main(String[] args) {
        for (String f : args) {
            listDir(f);
        }
    }

    private static void listDir(String dir) {
        File f = new File(dir);
        File[] list = f.listFiles();

        if (list == null) {
            return;
        }

        for (File entry : list) {
            System.out.println(entry.getName());
            if (entry.isDirectory()) {
                listDir(entry.getAbsolutePath());
            }
        }
    }
}