How do I iterate through the files in a directory in Java?

前端 未结 10 2111
星月不相逢
星月不相逢 2020-11-22 08:37

I need to get a list of all the files in a directory, including files in all the sub-directories. What is the standard way to accomplish directory iteration with Java?

相关标签:
10条回答
  • 2020-11-22 09:04

    For Java 7+, there is also https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html

    Example taken from the Javadoc:

    List<Path> listSourceFiles(Path dir) throws IOException {
       List<Path> result = new ArrayList<>();
       try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) {
           for (Path entry: stream) {
               result.add(entry);
           }
       } catch (DirectoryIteratorException ex) {
           // I/O error encounted during the iteration, the cause is an IOException
           throw ex.getCause();
       }
       return result;
    }
    
    0 讨论(0)
  • 2020-11-22 09:12

    You can use File#isDirectory() to test if the given file (path) is a directory. If this is true, then you just call the same method again with its File#listFiles() outcome. This is called recursion.

    Here's a basic kickoff example.

    public static void main(String... args) {
        File[] files = new File("C:/").listFiles();
        showFiles(files);
    }
    
    public static void showFiles(File[] files) {
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("Directory: " + file.getName());
                showFiles(file.listFiles()); // Calls same method again.
            } else {
                System.out.println("File: " + file.getName());
            }
        }
    }
    

    Note that this is sensitive to StackOverflowError when the tree is deeper than the JVM's stack can hold. You may want to use an iterative approach or tail-recursion instead, but that's another subject ;)

    0 讨论(0)
  • 2020-11-22 09:18

    Using org.apache.commons.io.FileUtils

    File file = new File("F:/Lines");       
    Collection<File> files = FileUtils.listFiles(file, null, true);     
    for(File file2 : files){
        System.out.println(file2.getName());            
    } 
    

    Use false if you do not want files from sub directories.

    0 讨论(0)
  • 2020-11-22 09:18

    As noted, this is a recursion problem. In particular, you may want to look at

    listFiles() 
    

    In the java File API here. It returns an array of all the files in a directory. Using this along with

    isDirectory()
    

    to see if you need to recurse further is a good start.

    0 讨论(0)
  • 2020-11-22 09:19

    You can also misuse File.list(FilenameFilter) (and variants) for file traversal. Short code and works in early java versions, e.g:

    // list files in dir
    new File(dir).list(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            String file = dir.getAbsolutePath() + File.separator + name;
            System.out.println(file);
            return false;
        }
    });
    
    0 讨论(0)
  • 2020-11-22 09:21

    I like to use Optional and streams to have a net and clear solution, i use the below code to iterate over a directory. the below cases are handled by the code:

    1. handle the case of empty directory
    2. Laziness

    but as mentioned by others, you still have to pay attention for outOfMemory in case you have huge folders

        File directoryFile = new File("put your path here");
        Stream<File> files = Optional.ofNullable(directoryFile// directoryFile
                                                              .listFiles(File::isDirectory)) // filter only directories(change with null if you don't need to filter)
                                     .stream()
                                     .flatMap(Arrays::stream);// flatmap from Stream<File[]> to Stream<File>
    
    0 讨论(0)
提交回复
热议问题