Java examples for File Path IO:Directory Content
To write your own filter, implementing the DirectoryStream.Filter<T> interface.
DirectoryStream.Filter<T> interface has a single method, accept().
import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) { Path path = Paths.get("C:/folder1/folder2/folder4"); // user-defined filter - only directories are accepted DirectoryStream.Filter<Path> dir_filter = new DirectoryStream.Filter<Path>() { public boolean accept(Path path) throws IOException { return (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)); }/* w ww.ja v a 2 s .c om*/ }; System.out.println("\nUser defined filter applied:"); try (DirectoryStream<Path> ds = Files.newDirectoryStream(path, dir_filter)) { for (Path file : ds) { System.out.println(file.getFileName()); } } catch (IOException e) { System.err.println(e); } } }