Using following code as test, I got the hang of the issue. The main difference between walk* and list is that list(dir) gives a stream of files in the directory dir, while both walk* method walk the subtree of its argument including the root of subtree—the directory itself.

The difference between walk and walkFileTree is that they supply different interfaces for walking the tree: walkFileTree takes FileVisitor, walk gives Stream<Path>.

Copypublic class FilesTest {
    public static void main(String[] args) {
        final String pwd = System.getProperty("user.dir");
        System.out.println("Working Directory = " + pwd);
        Path dir = Paths.get(pwd);
        System.out.println("Files.walk");
        try (Stream<Path> stream = Files.walk(dir, 1)) {
            stream.forEach(path -> FilesTest.doSomething("walk", path));
        } catch (IOException e) {
            logException("walk", e);
        }
        System.out.println("Files.walkFileTree");
        try {
            Files.walkFileTree(dir, Collections.emptySet(), 1, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    doSomething("visitFile", file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    logException("visitFile", exc);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            logException("walkFileTree", e);
        }
        System.out.println("Files.list");
        try (Stream<Path> stream = Files.list(dir)) {
            stream.forEach(path -> FilesTest.doSomething("dir", path));
        } catch (IOException e) {
            logException("dir", e);
        }
    }

    private static void logException(String title, IOException e) {
        System.err.println(title + "\terror: " + e);
    }

    private static void doSomething(String title, Path file) {
        System.out.println(title + "\t: " + file);
    }
}
Answer from andrybak on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › io › walk.html
Walking the File Tree (The Java™ Tutorials > Essential Java Classes > Basic I/O)
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);
🌐
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()); }
🌐
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.
🌐
Javadevcentral
javadevcentral.com › files walkfiletree
Files WalkFileTree | Java Developer Central
May 18, 2020 - The Files.walkFileTree static method from the NIO Files class is used to walk a file tree. The walk traverses the directory tree in a depth-first order.
🌐
Baeldung
baeldung.com › home › java › java io › a guide to nio2 filevisitor
A Guide To NIO2 FileVisitor | Baeldung
January 8, 2024 - public static void main(String[] args) { Path startingDir = Paths.get("C:/Users/user/Desktop"); String fileToSearch = "hibernate-guide.txt" FileSearchExample crawler = new FileSearchExample( fileToSearch, startingDir); Files.walkFileTree(startingDir, crawler); } You can play around with this example by changing the values of startingDir and fileToSearch variables. When fileToSearch exists in startingDir or any of its subdirectories, then you will get a success message, else, a failure message. In this article, we have explored some of the less commonly used features available in the Java 7 NIO.2 filesystem APIs, particularly the FileVisitor interface.
🌐
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.
Top answer
1 of 4
23

Using following code as test, I got the hang of the issue. The main difference between walk* and list is that list(dir) gives a stream of files in the directory dir, while both walk* method walk the subtree of its argument including the root of subtree—the directory itself.

The difference between walk and walkFileTree is that they supply different interfaces for walking the tree: walkFileTree takes FileVisitor, walk gives Stream<Path>.

Copypublic class FilesTest {
    public static void main(String[] args) {
        final String pwd = System.getProperty("user.dir");
        System.out.println("Working Directory = " + pwd);
        Path dir = Paths.get(pwd);
        System.out.println("Files.walk");
        try (Stream<Path> stream = Files.walk(dir, 1)) {
            stream.forEach(path -> FilesTest.doSomething("walk", path));
        } catch (IOException e) {
            logException("walk", e);
        }
        System.out.println("Files.walkFileTree");
        try {
            Files.walkFileTree(dir, Collections.emptySet(), 1, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    doSomething("visitFile", file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    logException("visitFile", exc);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            logException("walkFileTree", e);
        }
        System.out.println("Files.list");
        try (Stream<Path> stream = Files.list(dir)) {
            stream.forEach(path -> FilesTest.doSomething("dir", path));
        } catch (IOException e) {
            logException("dir", e);
        }
    }

    private static void logException(String title, IOException e) {
        System.err.println(title + "\terror: " + e);
    }

    private static void doSomething(String title, Path file) {
        System.out.println(title + "\t: " + file);
    }
}
2 of 4
4

Files.list simply delegates to Files.newDirectoryStream and exposes the underlying java.nio.file.DirectoryStream as a java.util.stream.Stream, so their functionality is basically the same except that Files.newDirectoryStream allows you to pass an optional DirectoryStream.Filter.

Files.walkFileTree additionally exposes BasicFileAttributes (such as lastModifiedTime, isRegularFile, and size). If you are going to need these attributes, it could be more convenient (and possibly more efficient) to get them from Files.walkFileTree instead of looking them up separately.

🌐
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 - Files.walk(...) returns a Stream<Path> object. It can recurse directories to a specified maximum depth. Files.walkFileTree(...) returns a Path object and takes a FileVisitor as a parameter.
🌐
Program Creek
programcreek.com › java-api-examples
Java Code Examples for java.nio.file.Files#walkFileTree()
*/ public static final void remove(Path path, boolean includeRootDir) { try { Files.walkFileTree(path, new RecursiveDirectoryRemover(includeRootDir ? null : path)); } catch (IOException exception) { Log.error(exception); } } Example 12 · @Test public void testZip() throws Exception { Path tkpath = bingo0Path.toPath(); File baseDir = new File(System.getProperty("java.io.tmpdir")); Path targetParent = Files.createTempDirectory(baseDir.toPath(), "tz"); try { Path target = new File(targetParent.toFile(),"tk.zip").toPath(); try (InputStream is = DirectoryZipInputStream.fromPath(tkpath)) { Files.copy(is, target); } // Unzip the zip file with system tools and compare with the source // directory.
Find elsewhere
🌐
LinkedIn
linkedin.com › pulse › walking-file-tree-java-incus-data-pty-ltd
Walking a File Tree in Java
June 13, 2023 - import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.FileSystems; import java.nio.file.Path; public class VisitingFileWalker { public static void main(String args[]) throws IOException { Path startDir; startDir = FileSystems.getDefault().getPath("c://<path>"); // OR // startDir = new File("c://<path>").toPath(); // the visitor CountFiles counter = new CountFiles(); // the walker Files.walkFileTree(startDir, counter); } // end of main } // end of class
🌐
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.
🌐
Javapapers
javapapers.com › java › walk-file-tree-with-java-nio
Walk File Tree with Java NIO - Javapapers
July 23, 2015 - Once the FileVisitor is implemented we can use the NIO util class Files to start the File walk. Files class has got the following two methods, walkFileTree(Path, FileVisitor) – pass the FileVisitor instance and the root file tree to walk.
🌐
ConcretePage
concretepage.com › java › jdk7 › traverse-directory-structure-using-files-walkfiletree-java-nio2
Traverse a Directory Structure Using Files.walkFileTree in Java NIO 2
December 2, 2013 - visitFile() is another generic ... for error logging which file has not been visited. Files.walkFileTree is the method that actually walks the file tree and invokes the FileVisitor methods as required....
🌐
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 - Files.walk(...) returns a Stream<Path> object. It can recurse directories to a specified maximum depth. Files.walkFileTree(...) returns a Path object and takes a FileVisitor as a parameter.
🌐
Straub
straub.as › java › history › walkfiletree.html
FileVisitor und die Methode Files.walkFileTree()
import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; import java.nio.file.Files; public class WalkFileTree_01 { public static void main(String[] args) { Path path = Paths.get("c:/tmp"); MyFileVisitor fileVisitor = new MyFileVisitor(); try { Files.walkFileTree(path, fileVisitor); System.out.print("found: " + fileVisitor.getFileCount() + " files in "); System.out.println(fileVisitor.getDirCount()+ " directories"); } catch(IOException ex) { ex.printStackTrace(); } } } Eine mögliche Ausgabe ·
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 8 )
April 21, 2026 - true if the file exists and is executable; false if the file does not exist, execute access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determined ... SecurityException - In the case of the default provider, and a security manager is installed, the checkExec is invoked to check execute access to the file. public static Path walkFileTree(Path start, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor) throws IOException
🌐
LinkedIn
linkedin.com › pulse › use-walkfiletree-show-your-java-files-cecil-westerhof
Use walkFileTree to Show Your Java Files
March 9, 2018 - System.setProperty("user.dir", javaDir); Go to the Java directory. for(String type : javaTypes) { Walk through the different types. int size; currentType = type; javaFiles = new ArrayList<>(); We use te diamond operator, so we do not need to specify the type of ArrayList. Files.walkFileTree(Paths.get(""), new FindJavaVisitor()); Put all the files from type currentType into javaFiles.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.nio.filenio.files.walkfiletree
Files.WalkFileTree Method (Java.Nio.FileNio) | Microsoft Learn
Walks a file tree. [Android.Runtime.Register("walkFileTree", "(Ljava/nio/file/Path;Ljava/nio/file/FileVisitor;)Ljava/nio/file/Path;", "", ApiSince=26)] public static Java.Nio.FileNio.IPath?
Top answer
1 of 3
10

I'm a little rusty in Java but here's a rough idea of where I think you're going:

import java.nio.files.*;
public class MyDirectoryInspector extends Object 
{
    public static void main(String[] args) {
        Path startPath = Paths.get("\\CallGuidesTXT\\");
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() { 
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException
            {
                String firstLine = Files.newBufferedReader(file, Charset.defaultCharset()).readLine();
                System.out.println(firstLine);
                return FileVisitResult.CONTINUE;
            }
        }); // <- you were missing a terminating ");"
    }
}

That should walk through the directories and print the first line of each file to std out. I haven't touched Java since 1.6 so the JDK7 stuff is a little new to me too. I think you are getting confused as to what's a class and what's an interface. In my example we start with a basic class called MyDirectoryInspector to avoid confusion. It's enough to give us a program entry point, the main method where we start the inspection. The call to Files.walkFileTree takes 2 parameters, a start path and a file visitor which I have inlined. (I think the inlining can be confusing to some people if you're not used to this style.) This is a way of defining the actual class right in the place where you wish to use it. You could have also defined the SimpleFileVisitor separately and just instantiated it for your call as follows:

import java.nio.files.*;
public class MyDirectoryInspector extends Object 
{
    public static void main(String[] args) {
        Path startPath = Paths.get("\\CallGuidesTXT\\");
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>());
    }
}

public class SimpleFileVisitor<Path>()) { 
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException
            {
                String firstLine = Files.newBufferedReader(file, Charset.defaultCharset()).readLine();
                System.out.println(firstLine);
                return FileVisitResult.CONTINUE;
            }
        }

It may make more sense, if you are just getting started, to keep things all separated. Define your classes without inlineing, take it one step at a time and make sure you understand each piece in isolation. My 2nd example gives you 2 individual pieces, a custom file visitor that can be used to print the 1st line of each file it visits and a program that uses it with the JDK Files class. Now let's look at another approach that omits the syntax:

import java.nio.files.*;
public class MyDirectoryInspector extends Object 
{
    public static void main(String[] args) {
        Path startPath = Paths.get("\\CallGuidesTXT\\");
        Files.walkFileTree(startPath, new SimpleFileVisitor());
    }
}

public class SimpleFileVisitor()) { 
            @Override
            public FileVisitResult visitFile(Object file, BasicFileAttributes attrs)
                throws IOException
            {
                String firstLine = Files.newBufferedReader((Path)file, Charset.defaultCharset()).readLine();
                System.out.println(firstLine);
                return FileVisitResult.CONTINUE;
            }
        }

With the generics left off you have to declare file parameter as an Object type and cast it later when you choose to use it. In general, you don't want to replace an interface definition with a class definition or confuse the two as they are used for entirely different purposes.

2 of 3
6

Java interface can not have any implementations (ie code) - only method signatures.

Try changing interface to class:

public class FileVisitor<T> {
    ...