June 23, 2022

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 recursively 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. See example.
  2. Java 7 onward you can use Files.walkFileTree() method which walks a file tree rooted at a given starting file. See example.
  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. See example.

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

public class ListDirStructure {

  public static void main(String[] args) {
    final String SOURCE_PATH = "F:/knpcode/Parent";
    File sourceDir = new File(SOURCE_PATH);
    listAllFiles(sourceDir);
  }

  public static void listAllFiles(File sourceDir){
    File[] fileList = sourceDir.listFiles();
    for(File file : fileList){
      // if directory, call method recursively
      if(file.isDirectory()){
        System.out.println("Sub Directory-" + file.getName());
        listAllFiles(file);
      }else{
        System.out.println("File-" + file.getAbsolutePath());
      }
    }
  }
}
Output
Sub Directory-Child
File-F:\knpcode\Parent\Child\hello.txt
File-F:\knpcode\Parent\Child\Project.docx
File-F:\knpcode\Parent\Test.txt

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().

For this example one more sub-directory Empty, which contains no files, is added inside Parent.

public class ListDirStructure {
  public static void main(String[] args) {
    final String SOURCE_PATH = "F:/knpcode/Parent";
    listAllFiles(SOURCE_PATH);
  }

  private static void listAllFiles(String sourceFolder){
    Path sourcePath = Paths.get(sourceFolder);
    // Walk the tree structure using WalkFileTree method
    try {
      Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>(){
        @Override
        // Before visiting the directory
        public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
          // Don't create dir for root folder as it is already created with .zip name 
          if(!sourcePath.equals(dir)){
            System.out.println("Directory- " + dir);
          }
          return FileVisitResult.CONTINUE;
        }
        @Override
        // For each visited file add it to zip entry
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
          System.out.println("File Name- " + sourcePath.relativize(file).toString());                 
          return FileVisitResult.CONTINUE;
        }
      });
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Output
Directory- F:\knpcode\Parent\Child
File Name- Child\hello.txt
File Name- Child\Project.docx
Directory- F:\knpcode\Parent\Empty
File Name- Test.txt

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

public class ListDirStructure {
  public static void main(String[] args) {
    final String SOURCE_PATH = "F:/knpcode/Parent";
    listAllFiles(SOURCE_PATH);
  }
    
  // Uses Files.walk method   
  public static void listAllFiles(String path){
    try(Stream<Path> filePaths = Files.walk(Paths.get(path))) {
      filePaths.forEach(filePath -> {
        if (Files.isRegularFile(filePath)) {
          System.out.println("File-" + filePath);
        }else{
          // check for source directory
          if(!filePath.toString().equals(path))
            System.out.println("Sub Directory-" + filePath);
        }
      });
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

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

No comments:

Post a Comment