How to List Files in a Directory Using Files.list

Java 8 introduced a number of utility classes intended to improve programmer productivity. The java.nio package was enhanced with a number of new methods. This article explores the list method in java.nio.file.Files class. This new method returns all the entries (files and directories) in the specified directory. However it is not recursive (for recursive use case there is another method named walk). Also note that the entries are loaded lazily for performance reasons.

How to List Files in a Directory Using Java 8 Features

The following example Java program uses Files.list method and has the following functions,

  • printlAllFiles - Prints all file names in the specified folder
  • printAllFilesInUpperCase - Prints all file names in upper case. This method illustrates the use of lambdas in Java 8.
  • printAllHiddenFiles - Prints all hidden file names in the specified folder. This method illustrates the use of filter function over the list function. Some of the other boolean functions available in Files class are isDirectory, isExecutable, isReadable, isRegularFile, isSymbolicLink and isWritable.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ListFilesInDirectory {

    public static void main(String[] args) throws Exception {
        // For windows replace with your folder
        // Example - c:\\jj.
        String rootFolder = "/Users/jj";
        printlAllFiles(rootFolder);
        printAllFilesInUpperCase(rootFolder);
        printAllHiddenFiles(rootFolder);
    }

    // Print all file names in the specified folder
    // Includes directories and hidden files
    // Nested sub-directories are not listed
    private static void printlAllFiles(String rootFolder) throws Exception {
        Files.list(Paths.get(rootFolder)).forEach(System.out::println);
    }

    // Print all file names in the specified folder in upper case
    private static void printAllFilesInUpperCase(String rootFolder) throws Exception {
        Files.list(Paths.get(rootFolder)).forEach(path -> {
            System.out.println(path.toString().toUpperCase());
        });
    }

    // Print all names of all hidden files in specified folder
    private static void printAllHiddenFiles(String rootFolder) throws Exception {
        Files.list(Paths.get(rootFolder)).filter(t -> {
            try {
                return Files.isHidden(t);
            } catch (IOException e) {
                return false;
            }
        }).forEach(System.out::println);
    }
}

 

References