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


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

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

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

final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);

文件。walk API可从Java 8获得。

try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
    paths
        .filter(Files::isRegularFile)
        .forEach(System.out::println);
} 

这个例子使用了API指南中推荐的try-with-resources模式。它确保在任何情况下流都将被关闭。


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

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

      }
    }
  }
}

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

         }
    }

}
}

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


防止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);

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

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

最佳,安德


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

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


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

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

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

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


}

/**
 * Function to read all mp3 files from sdcard and store the details in an
 * ArrayList
 */


public ArrayList<HashMap<String, String>> getPlayList() 
    {
        ArrayList<HashMap<String, String>> songsList=new ArrayList<>();
        File home = new File(MEDIA_PATH);

        if (home.listFiles(new FileExtensionFilter()).length > 0) {
            for (File file : home.listFiles(new FileExtensionFilter())) {
                HashMap<String, String> song = new HashMap<String, String>();
                song.put(
                        "songTitle",
                        file.getName().substring(0,
                                (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

                // Adding each song to SongList
                songsList.add(song);
            }
        }
        // return songs list array
        return songsList;
    }

    /**
     * Class to filter files which have a .mp3 extension
     * */
    class FileExtensionFilter implements FilenameFilter 
    {
        @Override
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3") || name.endsWith(".MP3"));
        }
    }

你可以过滤任何文本文件或任何其他扩展..把它换成。mp3


只需使用“文件”遍历所有“文件”。walkFileTree (java7)

Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        System.out.println("file: " + file);
        return FileVisitResult.CONTINUE;
    }
});

在Java 8中,你可以这样做

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

它将打印文件夹中的所有文件,同时排除所有目录。如果你需要一个列表,下面的方法可以做到:

Files.walk(Paths.get("/path/to/folder"))
     .filter(Files::isRegularFile)
     .collect(Collectors.toList())

如果你想返回List<File>而不是List<Path>,只需映射它:

List<File> filesInFolder = Files.walk(Paths.get("/path/to/folder"))
                                .filter(Files::isRegularFile)
                                .map(Path::toFile)
                                .collect(Collectors.toList());

您还需要确保关闭流!否则,您可能会遇到一个异常,告诉您打开的文件太多。阅读这里了解更多信息。


从Test文件夹中列出类路径内的文件

import java.io.File;
import java.io.IOException;

public class Hello {

    public static void main(final String[] args) throws IOException {

        System.out.println("List down all the files present on the server directory");
        File file1 = new File("/prog/FileTest/src/Test");
        File[] files = file1.listFiles();
        if (null != files) {
            for (int fileIntList = 0; fileIntList < files.length; fileIntList++) {
                String ss = files[fileIntList].toString();
                if (null != ss && ss.length() > 0) {
                    System.out.println("File: " + (fileIntList + 1) + " :" + ss.substring(ss.lastIndexOf("\\") + 1, ss.length()));
                }
            }
        }


    }


}

我认为这是读取文件夹和子文件夹中的所有文件的好方法

private static void addfiles (File input,ArrayList<File> files)
{
    if(input.isDirectory())
    {
        ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.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));
            }
        }
    }
    if(input.isFile())
    {
        files.add(input);
    }
}

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

关于这个主题的所有使用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方法在流操作完成后调用。


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

虽然我同意Rich, Orian和其他人使用:

    final File keysFileFolder = new File(<path>); 
    File[] fileslist = keysFileFolder.listFiles();

    if(fileslist != null)
    {
        //Do your thing here...
    }

出于某种原因,这里所有的例子都使用绝对路径(即从根目录开始,或者,对于windows..)

我想补充的是,也可以使用相对路径。 所以,如果你的pwd(当前目录/文件夹)是folder1,你想要解析folder1/子文件夹,你只需写(在上面的代码中代替):

    final File keysFileFolder = new File("subfolder");

Java 8 Files.walk(..)很好,当你感到痛苦时,它不会抛出避免Java 8 Files.walk(..)终止原因(Java .nio.file. accessdeniedexception)。

这里有一个安全的解决方案,虽然没有Java 8Files.walk(..)那么优雅:

int[] count = {0};
try {
    Files.walkFileTree(Paths.get(dir.getPath()), new HashSet<FileVisitOption>(Arrays.asList(FileVisitOption.FOLLOW_LINKS)),
            Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file , BasicFileAttributes attrs) throws IOException {
                    System.out.printf("Visiting file %s\n", file);
                    ++count[0];

                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file , IOException e) throws IOException {
                    System.err.printf("Visiting failed for %s\n", file);

                    return FileVisitResult.SKIP_SUBTREE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir , BasicFileAttributes attrs) throws IOException {
                     System.out.printf("About to visit directory %s\n", dir);
                    return FileVisitResult.CONTINUE;
                }
            });
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

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


上面有很多很好的答案,这里有一种不同的方法:在maven项目中,您放在resources文件夹中的所有内容都会默认复制到target/classes文件夹中。查看在运行时可用的内容

 ClassLoader contextClassLoader = 
 Thread.currentThread().getContextClassLoader();
    URL resource = contextClassLoader.getResource("");
    File file = new File(resource.toURI());
    File[] files = file.listFiles();
    for (File f : files) {
        System.out.println(f.getName());
    }

现在要从一个特定的文件夹中获取文件,假设你的资源文件夹中有一个名为“res”的文件夹,只需替换:

URL resource = contextClassLoader.getResource("res");

如果你想访问你的com.companyName包,那么:

contextClassLoader.getResource("com.companyName");

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

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

这将很好地工作:

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

}

您可以将文件路径设置为参数,并创建包含所有文件路径的列表,而不必手动将其放入列表中。然后使用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
                 }}}

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

}

给定一个baseDir,列出它下面的所有文件和目录,迭代编写。

    public static List<File> listLocalFilesAndDirsAllLevels(File baseDir) {

    List<File>  collectedFilesAndDirs   = new ArrayList<>();
    Deque<File> remainingDirs           = new ArrayDeque<>();

    if(baseDir.exists()) {
        remainingDirs.add(baseDir);

        while(!remainingDirs.isEmpty()) {
            File dir = remainingDirs.removeLast();
            List<File> filesInDir = Arrays.asList(dir.listFiles());
            for(File fileOrDir : filesInDir)  {
                collectedFilesAndDirs.add(fileOrDir);
                if(fileOrDir.isDirectory()) {
                    remainingDirs.add(fileOrDir);
                }
            }
        }
    }

    return collectedFilesAndDirs;
}

一个注释根据获得目录中的所有文件。 方法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

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

eg:

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

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


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