How to List All The Files in a Directory in Java

Some times you may need to list all the files in a directory to get a specific file, to read all the files or to zip a folder where you need to go through the whole folder tree structure. This post shows how you can list all the files and sub-directories in a directory in Java.

List files and sub-directories with in a directory in Java

For listing the folder tree structure which includes the sub-directories and all the files you can use one of the following options-

  1. Using File.listFiles() method which returns an array of abstract pathnames denoting the files in the directory. Then you can iterate the array to list the files, you will have to recursively call your method to list files with in the sub-directories.
  2. Java 7 onward you can use Files.walkFileTree method which walks a file tree rooted at a given starting file.
  3. Java 8 onward you can use Files.walk() method which returns the Path objects as stream by walking the file tree rooted at a given starting file.

Directory structure used

Java programs shown here to list all the files in a directory in Java use the following directory structure.

list files in a folder in Java

With in the parent folder there is one sub folder Child with two files and one file is stored in the parent folder.

Listing all the files in Java using File.listFiles() method

Output

Listing all the files in Java using Files.walkFileTree() method

One of the argument of this method is a FileVisitor interface. You do need to provide implementation of this interface as per your requirement.

FileVisitor interface has four methods, for listing files in a folder you do need to implement two of them; preVisitDirectory and visitFile.

Output

Listing all the files in Java using Files.walk() method

That’s all for the topic How to List All The Files in a Directory in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.