🌐
Medium
medium.com › @AlexanderObregon › javas-files-walk-method-explained-570d8a67247d
Java’s Files.walk() Method Explained | Medium
September 3, 2024 - Files.walk() offers several strategies to manage resources and handle vast file systems without running into performance issues. One of the best practices when working with large directories is to ensure proper resource management. Using try-with-resources is a simple and effective way to automatically close the stream after processing: import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; import java.util.stream.Stream; public class FilesWalkExample { public static void main(String[] args) { Path start = Paths.get("path/to/start/directory"); try (Stream<Path> stream = Files.walk(start)) { stream.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } }
🌐
Mkyong
mkyong.com › home › java › java files.walk examples
Java Files.walk examples - Mkyong.com
December 2, 2020 - The `Files.walk` API is available since Java 8; it helps to walk a file tree at a given starting path.
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › io › walk.html
Walking the File Tree (The Java™ Tutorials > Essential Java Classes > Basic I/O)
If you want to ensure that this method walks the entire file tree, you can specify Integer.MAX_VALUE for the maximum depth argument. You can specify the FileVisitOption enum, FOLLOW_LINKS, which indicates that symbolic links should be followed. This code snippet shows how the four-argument method can be invoked: import static java.nio.file.FileVisitResult.*; Path startingDir = ...; EnumSet<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS); Finder finder = new Finder(pattern); Files.walkFileTree(startingDir, opts, Integer.MAX_VALUE, finder);
🌐
ZetCode
zetcode.com › java › fileswalk
Java Files.walk - listing files in Java with Files.walk
July 7, 2024 - There are two overloaded Files.walk methods; one of them takes the maxDepth parameter, which sets the maximum number of levels of directories to visit. By default, symbolic links are not automatically followed by this method. If the options parameter contains the FOLLOW_LINKS option then symbolic links are followed. The first example shows regular files in the specified directory. ... import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; void main() throws IOException { var dirName = "C:/Users/Jano/Downloads"; try (Stream<Path> paths = Files.walk(Paths.get(dirName), 2)) { paths.filter(Files::isRegularFile) .forEach(System.out::println); } }
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 8 )
April 21, 2026 - This method walks a file tree rooted at a given starting file. The file tree traversal is depth-first with the given FileVisitor invoked for each file encountered. File tree traversal completes when all accessible files in the tree have been visited, or a visit method returns a result of TERMINATE.
🌐
Mkyong
mkyong.com › home › java › how to traverse all files from a folder in java
How to traverse all files from a folder in Java - Mkyong.com
May 17, 2024 - In Java, we can use the Files.walk() API to traverse all files from a folder and its subfolders.
🌐
Medium
medium.com › @AlexanderObregon › javas-files-walkfiletree-method-explained-6660bebfa626
Java’s Files.walkFileTree() Method Explained | Medium
November 14, 2024 - By default, it explores all levels within a directory tree, allowing you to customize actions for each file or folder encountered during traversal. Here’s the basic syntax for calling walkFileTree(): import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; Path startPath = Paths.get("path/to/start/directory"); try { Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { // Handle the file here System.out.println("Visited file: " + file); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { System.err.println("Error traversing directory: " + e.getMessage()); }
🌐
Baeldung
baeldung.com › home › java › java io › list files in a directory in java
List Files in a Directory in Java | Baeldung
January 8, 2024 - The walk() method traverses the directory at the depth provided as its argument. Here, we traversed the file tree and collected the names of all the files into a Set.
🌐
Javaprogramto
javaprogramto.com › 2020 › 02 › java-8-files-walk.html
Java 8 Files walk() Examples JavaProgramTo.com
February 25, 2020 - walk() method is part of the Files class and java.nio.file package. This method is used to walk through any given directory and retrieves Stream<Path> as the return value.
Find elsewhere
🌐
LinkedIn
linkedin.com › pulse › walking-file-tree-java-part-2-incus-data-pty-ltd
Walking a File Tree in Java - Part 2
June 28, 2023 - Last week’s program used two primary classes. The walkFileTree() method of the Files class visited each file in the tree (the data structure). The CountFiles class defined the operations (the algorithm) to be run on each file (the element) visited.
Top answer
1 of 3
42
Files.walk(Paths.get("/path/to/stuff/"))
     .filter(p -> p.toString().endsWith(".ext"))
     .map(p -> p.getParent().getParent())
     .distinct()
     .forEach(System.out::println);

This filters all files that have the extension and gets the parent path of their directory. distinct ensures that every path is used only once.

2 of 3
4

You are invoking the method printIfArtifactVersionDirectory for all visited directories. I did a little change to make it obvious:

static void printIfArtifactVersionDirectory(Path path) {
    System.out.println("--- " + path);
    ...
}

With that additional output you will get:

--- C:\Projects\stuff
--- C:\Projects\stuff\org
--- C:\Projects\stuff\org\foo
--- C:\Projects\stuff\org\foo\bar
--- C:\Projects\stuff\org\foo\bar\1.2.3
C:\Projects\stuff\org\foo\bar
--- C:\Projects\stuff\org\foo\bar\1.2.4
C:\Projects\stuff\org\foo\bar
--- C:\Projects\stuff\org\foo\bar\blah
--- C:\Projects\stuff\org\foo\bar\blah\2.1
C:\Projects\stuff\org\foo\bar\blah
--- C:\Projects\stuff\org\foo\bar\blah\2.2
C:\Projects\stuff\org\foo\bar\blah

So you get the output as often as you have artifact version directories. If you want to remember that you already did the output for one directory, you must make store this information somewhere. One quick implementation could be:

static class Foo {
    private static final Set<Path> visited = new HashSet<>();

    static void printIfArtifactVersionDirectory(Path path) {
        ...
        Path parent = path.getParent();
        if (!filePaths.isEmpty() && !visited.contains(parent)) {
            visited.add(parent);
            System.out.println(parent);
        }
    }
}

With this you get the expected output:

C:\Projects\stuff\org\foo\bar
C:\Projects\stuff\org\foo\bar\blah

A better solution would be to use the set for storing the visited parents and only print them after visiting them all:

static class PathStore {
    private final Set<Path> store = new HashSet<>();

    void visit(Path path) {
        File f = path.toAbsolutePath().toFile();
        List<String> filePaths = Arrays.asList(f.list(new MyExtFilenameFilter()));
        if (!filePaths.isEmpty()) {
            store.add(path.getParent());
        }
    }

    void print() {
        store.forEach(System.out::println);
    }
}

Usage:

PathStore pathStore = new PathStore();
Files.walk(Paths.get("/path/to/stuff/"))
        .filter(Files::isDirectory)
        .forEach(pathStore::visit);
pathStore.print();
🌐
LogicBig
logicbig.com › how-to › code-snippets › jcode-java-io-files-walk.html
Java IO & NIO - Files.walk() Examples
Java IO & NIO&nbsp;Java Java API · Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file
🌐
Dev.java
dev.java › learn › java-io › file-system › walking-tree
Walking the File Tree - Dev.java
January 4, 2024 - How to walk a file tree, visiting every file and directory recursively with a file visitor.
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
Reddit
reddit.com › r/learnjava › efficient processing without multiple files walk
r/learnjava on Reddit: Efficient processing without multiple Files walk
April 22, 2023 -

I am writing a simple program that walks the file tree to generate various statistics about the files.

For example:

try (Stream<Path> walk = Files.walk(PATH)) {
    // Find all directories
    List<Path> dirs = walk.filter(Files::isDirectory).collect(Collectors.toList());

    // Find all files
    List<Path> files = walk.filter(Files::isRegularFile).collect(Collectors.toList());

    // Find zip archive files
    List<Path> zips = walk.filter(
        p -> p.getFileName().toString().toLowerCase().endsWith(".zip"))
        .collect(Collectors.toList());

    // Find files bigger than 1 Mb
    List<Path> filesBiggerThan1Mb = walk.filter(p -> {
        try {
            return Files.size(p) > 1048576;
        } catch (IOException e) {					
            e.printStackTrace();
            return false;
        }
    }).collect(Collectors.toList());

    // Get total size of all files
    long totalSize = walk.filter(Files::isRegularFile).mapToLong(p -> {
        try {
            return Files.size(p);
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }).sum();
}

Currently it walks the file tree multiple times by reusing the walk object. Although it seems like either the JRE or os does some caching in memory, and subsequent Files walks are much faster, I am wondering how I can write it in a different way to only need to invoke Files walk only once and do everything in 1 sweep.

🌐
Medium
rameshfadatare.medium.com › how-to-efficiently-traverse-directories-in-java-using-files-walk-a5d909583400
How to Efficiently Traverse Directories in Java Using Files.walk() | by Ramesh Fadatare | Medium
February 28, 2025 - Learn how Java’s Files.walk() simplifies directory traversal for large file systems. Discover efficient techniques for listing, filtering…
🌐
LinkedIn
linkedin.com › pulse › walking-file-tree-java-incus-data-pty-ltd
Walking a File Tree in Java
June 13, 2023 - The walkFileTree() method walks a file tree starting at a given directory. It traverses the file tree, calling the methods of a FileVisitor object for each file it comes across.
🌐
Blogger
java8example.blogspot.com › 2019 › 08 › java-8-files-walk.html
Java 8 Files walk() Examples Java8Example
August 14, 2019 - A quick guide to Java 8 Files API walk() method with examples. Files.walk() is used to get the file names, folder names and pattern match for a given directory.
🌐
Incus Data
incusdata.com › home › walking a file tree in java – part 2
Walking a File Tree in Java - Part 2 • 2026 • Incus Data Programming Courses
June 28, 2023 - Last week’s program used two primary classes. The walkFileTree() method of the Files class visited each file in the tree (the data structure). The CountFiles class defined the operations (the algorithm) to be run on each file (the element) visited.