Tuesday, September 3, 2013

SimpleFileVisitor example

java.nio.file.SimpleFileVisitor is a simple visitor of files with default behavior to visit all files and to re-throw I/O errors.

Simple example using SimpleFileVisitor.
package java_simplefilevisitor;

import java.io.IOException;
import java.nio.file.FileVisitResult;
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;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_SimpleFileVisitor {
    
    public static class MySimpleFileVisitor extends SimpleFileVisitor<Path> {

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) 
                throws IOException {
            System.out.format("preVisitDirectory: %s\n", dir);
            return super.preVisitDirectory(dir, attrs);
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
                throws IOException {
            System.out.format("visitFile: %s\n", file);
            return super.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) 
                throws IOException {
            System.out.format("visitFileFailed: %s\n", file);
            return super.visitFileFailed(file, exc);
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) 
                throws IOException {
            System.out.format("postVisitDirectory: %s\n", dir);
            return super.postVisitDirectory(dir, exc);
        }
        
    }

    public static void main(String[] args) {
        Path path = Paths.get("/home/eric/NetBeansProjects/Java_SimpleFileVisitor");
        MySimpleFileVisitor mySimpleFileVisitor = new MySimpleFileVisitor();
        
        try {
            Files.walkFileTree(path, mySimpleFileVisitor);
        } catch (IOException ex) {
            Logger.getLogger(Java_SimpleFileVisitor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


SimpleFileVisitor
SimpleFileVisitor example


Reference:
- Class SimpleFileVisitor
- Walking the File Tree


No comments:

Post a Comment