Java DirectoryStreamFilter-class And Method Code Example


Here is an example of how to use the DirectoryStreamFilter class from the Apache Commons IO library to filter the contents of a directory:

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DirectoryFilterExample {
    public static void main(String[] args) {
        try {
            // Define the directory to be filtered
            String directory = "/path/to/directory";

            // Create a DirectoryStream instance
            DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(directory), new DirectoryStreamFilter());

            // Print the filtered contents of the directory
            for (Path path : stream) {
                System.out.println(path.getFileName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class DirectoryStreamFilter implements DirectoryStream.Filter<Path> {
    @Override
    public boolean accept(Path path) {
        // Filter logic goes here
        // For example, only return true for files ending with ".txt"
        if (path.toString().endsWith(".txt")) {
            return true;
        }
        return false;
    }
}

This example filters the contents of the directory and only prints the file names of the files that pass the filter. You can customize the filtering logic to suit your needs by modifying the accept method of the DirectoryStreamFilter class