Java.Streams.How to select all elements of a certain directory by criterion (for example, with a certain extension)?

To select all files in a specific directory that match a certain criterion — like a file extension — you can use either:

  • FileFilter or FilenameFilter (from java.io)
  • Java 8 Stream API
  • Java NIO DirectoryStream (from java.nio.file)

✅ Option 1: Using File.listFiles(FileFilter)

🔹 Filter by extension: .txt

import java.io.*;

public class FilterByExtension {
    public static void main(String[] args) {
        File dir = new File("your-directory-path");

        File[] txtFiles = dir.listFiles(file -> file.getName().endsWith(".txt"));

        if (txtFiles != null) {
            for (File file : txtFiles) {
                System.out.println(file.getName());
            }
        }
    }
}

Uses FileFilter via lambda (file -> condition)

Can be customized easily for other criteria

✅ Option 2: Using FilenameFilter

File[] txtFiles = dir.listFiles((dir1, name) -> name.endsWith(".txt"));
  • Similar result, but you get file name as String
  • Slightly more limited (no access to File.length() or isDirectory())

✅ Option 3: Java NIO — DirectoryStream

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.DirectoryStream.Filter;

public class NioFilter {
    public static void main(String[] args) throws IOException {
        Path dir = Paths.get("your-directory-path");

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.txt")) {
            for (Path file : stream) {
                System.out.println(file.getFileName());
            }
        }
    }
}
Uses glob patterns (e.g., *.txt)

More powerful for complex path operations

🧵 TL;DR

Method	API	Pros	Use When
listFiles(FileFilter)	java.io	Simple, direct, supports lambdas	Filtering by file properties
listFiles(FilenameFilter)	java.io	Simple, filters by name	Just need the name
DirectoryStream	java.nio.file	Advanced, glob patterns, efficient	Need flexibility or performance
  • Uses glob patterns (e.g., *.txt)
  • More powerful for complex path operations

🧵 TL;DR

MethodAPIProsUse When
listFiles(FileFilter)java.ioSimple, direct, supports lambdasFiltering by file properties
listFiles(FilenameFilter)java.ioSimple, filters by nameJust need the name
DirectoryStreamjava.nio.fileAdvanced, glob patterns, efficientNeed flexibility or performance
This entry was posted in Без рубрики. Bookmark the permalink.