HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java 8 / Java 8 List All Files In Directory – Six Examples

Java 8 List All Files In Directory – Six Examples

Learn to use Java 8 APIs along with Files.list() and DirectoryStream to list all files present in a directory, including hidden files, recursively.

1. List all files and sub-directories using Files.list()

Files.list() method to list all file names and sub-directories in current directory.

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

 Output:

.\filename1.txt
.\directory1
.\filename2.txt
.\Employee.java

2. List only files inside directory using filter expression

You can use filters to filter out sub-directories and print only file names, if you need it.

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

 Output:

.\filename1.txt
.\filename2.txt
.\Employee.java

To list files in a different directory, we can replace "." with the full path of the directory we desire.

3. List files and sub-directories with Files.newDirectoryStream()

Java provides a more flexible way of traversing a directory content using Files.newDirectoryStream().

Please note that if we’re working with a large directory, then using DirectoryStream actually make code faster.

Files.newDirectoryStream(Paths.get("."))
		.forEach(System.out::println);

 Output:

.\filename1.txt
.\directory1
.\filename2.txt
.\Employee.java

4. List only files with Files.newDirectoryStream()

To list out only files and excluding all directories from stream, use path filter as second argument.

Files.newDirectoryStream(Paths.get("."), path -> path.toFile().isFile())
		.forEach(System.out::println);

Output:

.\filename1.txt
.\filename2.txt
.\Employee.java

5. List files of certain extention with Files.newDirectoryStream()

You can change the path filter expression passed in second argument to get files of certain extension only.

Files.newDirectoryStream(Paths.get("."),
		path -> path.toString().endsWith(".java"))
		.forEach(System.out::println);

Output:

.\Employee.java

6. Find all hidden files in directory

To find all hidden files, you can use filter expression file -> file.isHidden() in any of above example.

Or you can use this shortcut method.

final​ ​File​​[]​ files = ​new​ ​File​(​"."​).listFiles(file -> file.isHidden());
//or
final​ ​File​​[]​ files = ​new​ ​File​(​"."​).listFiles(​File​::isHidden);

In above examples, we learn to use java 8 APIs list or iterate files in directory recursively on various search criteria. Feel free to modify the code and play with it.

Happy Learning !!

References:

DirectoryStream
Files.list() method

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. ReddiSeharReddy

    November 27, 2019

    Hi,
    how to apply filter to get the list of files created between two dates.

    Could you please suggest on this.

    • ReddiSeharReddy

      November 27, 2019

      Files.newDirectoryStream(Paths.get(directory),
      path -> path.toFile().lastModified() > sd.getTime() && path.toFile().lastModified() < ed.getTime());

  2. Rich K

    October 27, 2018

    Alex B, that code does not demonstrate what list the filenames go to. Where is the list variable ?

  3. Anubhav Gupta

    February 16, 2018

    Here is the code for reading filename and store them in list.

    List fileNamesList = new ArrayList();
          Files.newDirectoryStream(Paths.get(dir), 
          path -> path.toString().endsWith(".java")).forEach(filePath -> fileNamesList.add(filePath.toString()));
    
  4. jack

    February 6, 2018

    I appreciate the post.

    But the code in “Find all hidden files in directory” section gives syntax error.

    And, its sad that you didn’t tell how to capture the file names in a list or something else (will be helpful for the people who are learning java 8). In real world, we don’t need to read the file names just to sysout.

    • Anubhav Gupta

      February 16, 2018

      Here is the code for reading file names and store them in list.

      List fileNamesList = new ArrayList();
      		Files.newDirectoryStream(Paths.get(dir), path -> path.toString().endsWith(filenameFilter)).forEach(filePath -> fileNamesList.add(filePath.toString()));
      
      • Alex B

        March 12, 2018

        You’re actually better off doing something like this:

                    Files.list(Paths.get(dir))
                            .map(Path::toFile)
                            .map(File::getAbsolutePath)
                            .collect(Collectors.toList())

        Which allows you to use the streams api to transform/filter the list before you collect it.

        • sekaijin

          September 18, 2019

          Files.list(Paths.get(dir))
                  .map(Path::toAbsolutePath)
                  .collect(Collectors.toList())
      • Dhiraj Kumar

        March 21, 2020

        nice code

Comments are closed on this article!

Search Tutorials

Java 8 Tutorial

  • Java 8 Features
  • Java 8 forEach
  • Java 8 Stream
  • Java 8 Boxed Stream
  • Java 8 Lambda Expression
  • Java 8 Functional Interface
  • Java 8 Method Reference
  • Java 8 Default Method
  • Java 8 Optional
  • Java 8 Predicate
  • Java 8 Regex as Predicate
  • Java 8 Date Time
  • Java 8 Iterate Directory
  • Java 8 Read File
  • Java 8 Write to File
  • Java 8 WatchService
  • Java 8 String to Date
  • Java 8 Difference Between Dates
  • Java 8 Join Array
  • Java 8 Join String
  • Java 8 Exact Arithmetic
  • Java 8 Comparator
  • Java 8 Base64
  • Java 8 SecureRandom
  • Internal vs External Iteration

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces