6.4. Recursively access a directory tree - Source Code

Code:


package c6.s4;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * @author Mikalai Zaikin
 */
public class FileVisitorExample {

    public static void main(String... args) throws IOException {

        FileVisitor<Path> myFileVisitor = new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                System.out.println(String.format("Before visit the '%s' directory", dir));
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attribs) {
                System.out.println(String.format("Visiting file '%s' which has size %d bytes", file, attribs.size()));
                return FileVisitResult.CONTINUE;
            }
        };

        Path headDir = Paths.get("C:\\home");

        Files.walkFileTree(headDir, myFileVisitor);
    }
}

					

output:

Before visit the 'C:\home' directory
Before visit the 'C:\home\zaikin' directory
Before visit the 'C:\home\zaikin\foo' directory
Before visit the 'C:\home\zaikin\foo\company' directory
Visiting file 'C:\home\zaikin\foo\company\readme.txt' which has size 2 bytes
Visiting file 'C:\home\zaikin\foo\resume.doc' which has size 0 bytes
Before visit the 'C:\home\zaikin\foo\sample' directory
Visiting file 'C:\home\zaikin\foo\test.txt' which has size 7 bytes
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide