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.

Answer from a better oliver on Stack Overflow
🌐
Mkyong
mkyong.com › home › java › java files.walk examples
Java Files.walk examples - Mkyong.com
December 2, 2020 - This example uses Files.walk to find all text files .txt from a path. ... package com.mkyong.io.api; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FilesWalkExample4 { public static void main(String[] args) throws IOException { Path path = Paths.get("C:\\test\\"); List<Path> paths = findByFileExtension(path, ".txt"); paths.forEach(x -> System.out.println(x)); } public static List<Path> findByFileExtension(Path path, String fileE
🌐
Medium
medium.com › @AlexanderObregon › javas-files-walk-method-explained-570d8a67247d
Java’s Files.walk() Method Explained | Medium
September 3, 2024 - For example, you might want to find all .java files in a directory tree: import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; public class FilesWalkExample { public static void main(String[] args) { Path start = Paths.get("path/to/start/directory"); try { Files.walk(start) .filter(path -> path.toString().endsWith(".java")) .forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } }
🌐
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); } }
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();
🌐
Javaprogramto
javaprogramto.com › 2020 › 02 › java-8-files-walk.html
Java 8 Files walk() Examples JavaProgramTo.com
February 25, 2020 - Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative ...
🌐
Dev.java
dev.java › learn › java-io › file-system › walking-tree
Walking the File Tree - Dev.java
January 4, 2024 - Here is an example that extends SimpleFileVisitor to print all entries in a file tree. It prints the entry whether the entry is a regular file, a symbolic link, a directory, or some other "unspecified" type of file.
🌐
Program Creek
programcreek.com › java-api-examples
Java Code Examples for java.nio.file.Files#walk()
Stream<Path> silentFilesWalk(Path dir) throws IllegalStateException { try { return Files.walk(dir); } catch (IOException ex) { throw new IllegalStateException(ex); } } ... /** * Requests that the resource denoted by the given path be deleted upon (normal) termination of the Java virtual * machine.
Find elsewhere
🌐
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
🌐
Medium
medium.com › @AlexanderObregon › javas-files-walkfiletree-method-explained-6660bebfa626
Java’s Files.walkFileTree() Method Explained | Medium
November 14, 2024 - For example, if you need to backup files based on a specific condition, you can use the visitFile() method to check for these conditions and copy qualifying files to an archive directory. import java.io.IOException; import java.nio.file.*; import ...
🌐
Hotexamples
java.hotexamples.com › examples › java.nio.file › Files › walk › java-files-walk-method-examples.html
Java Files.walk Examples, java.nio.file.Files.walk Java Examples - HotExamples
Example #3 · 0 · Show file · File: LocalFileSystemTest.java · Project: peter-mount/filesystem · private void walk(String authority, Path root, String prefix, int count) throws IOException { Path cachePath = BASE_PATH.resolve(authority); Path dirPath = Paths.get(cachePath.toString(), root.toString()); Set<String> fileNames = Files.walk(dirPath) .filter(p -> p.toString().endsWith(".txt")) .map(p -> Paths.get(p.toAbsolutePath().toString())) .map(cachePath::relativize) .map(Object::toString) .collect(Collectors.toSet()); assertFalse(fileNames.isEmpty()); Set<String> expected = IntStream.range
🌐
Blogger
java8example.blogspot.com › 2019 › 08 › java-8-files-walk.html
Java 8 Files walk() Examples Java8Example
August 14, 2019 - Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.
🌐
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.
🌐
Java2s
java2s.com › example › java-api › java › nio › file › files › walk-2-1.html
Example usage for java.nio.file Files walk - Java2s
From source file:com.ejie.uda.jsonI18nEditor.Editor.java · public void importResources(Path dir) { Stream<Path> filter; try {/* w w w . j a va 2 s. c o m*/ if (!closeCurrentSession()) { return; } if (Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) { reset(); resourcesDir = dir; filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path)); } else { reset(); // Se ha arrastrado un fichero de 18n individual, se debe de obtener los recursos relacionados con el bundle al que pertenece.
🌐
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 - But it’s overkill for the example in this post. Let’s first do a simple comparison between the Files.list() and the Files.walk() methods: import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.Files; public class ListAndWalkTest { public static void main(String args[]) { final String startDir = "c://<path>"; // change this first!
🌐
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 - But it’s overkill for the example in this post. Let’s first do a simple comparison between the Files.list() and the Files.walk() methods: import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.Files; public class ListAndWalkTest { public static void main(String args[]) { final String startDir = "c://<path>"; // change this first!
🌐
Kodejava
kodejava.org › how-do-i-use-files-walk-method-to-read-directory-contents
How do I use Files.walk() method to read directory contents? - Learn Java by Examples
June 21, 2024 - package org.kodejava.io; import ... how deep into the directory structure you want to go. For example, Files.walk(start, 2) would only go two levels deep....
🌐
Fullstacksref
fullstacksref.com › 2020 › 04 › java-files-walk-examples.html
Java Files walk examples
result = walk.filter(Files::isRegularFile) .map(x -> x.getFileName().toString()) .collect(Collectors.toList()); result.forEach(System.out::println); return result; } } This method will list all directories along with files inside them.
🌐
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 - The following example uses the Files.walk() API to traverse and collect all the file names from a folder and its subfolders. In the final step, the program will print out the total number of files collected and all the filenames.
🌐
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.