Walking the file tree

10 0 0
                                    

FileVisitor - this is an interface that is implemented if you wanted to walk in a file tree.

Four requirements that needs implementation

1. preVisitDirectory() - called before all the directories entries are visited

2. postVisitDirectory() - called after all the directories entries are visited

3. visitFile() - call the file being visited

4. visitFileFailed() - called when the file cannot be accessed

Each process returned FileVisitor. You can control the walking through this returned values.

1. CONTINUE

2. TERMINATE

3. SKIP_SUBTREE

4. SKIP_SIBLINGS


SimpleFileVisitor - is a class which implements the FileVisitor interface. If you don't want to implement all the requirements, use this class.

Two methods to walk the file tree after implementing the file visitor

1. Files.walkFileTree(Path, FileVisitor)

2. Files.walkFileTree(Path, Set<FileVisitOption>, int, FileVisitor)



==================

import java.io.IOException;

import java.nio.file.*;

import java.nio.file.attribute.BasicFileAttributes;

public class Practice1 extends SimpleFileVisitor<Path> {

    public static void main(String[] args) throws IOException {

        Path thePath = Paths.get("README.md");

        Practice1 obj = new Practice1();

        BasicFileAttributes attributes = Files.readAttributes(thePath, BasicFileAttributes.class);

        obj.visitFile(thePath, attributes);

        System.out.println("Walking: " + Files.walkFileTree(thePath, obj));

    }

    @Override

    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {

        if(attrs.isRegularFile()){

            System.out.println("The File " + file + " is a regular file.");

            System.out.println("The size is " + attrs.size());

        }else{

            System.out.println("Note a regular file: " + file);

        }

        return FileVisitResult.TERMINATE;

    }

}

==================

Result:

The File README.md is a regular file.

The size is 72

The File README.md is a regular file.

The size is 72

Walking: README.md


Note: I will continue updating this but not that much now since I will be focusing on Spring and Android.

Java ProgrammingWhere stories live. Discover now