FileVisitor from NIO.2 File System API in Java 7

As a part of project Coin ( Language changes ) in Java 7 improved version of file operation APIS has introduced, java.nio.file. There are many new functionalities has been introduced for ease of day to day programming, FileVisitor is one these APIs.

As explained above, new interface java.nio.file.FileVisitor has been introduced for traversing the file system. It has methods like preVisitDirectory(), postVisitDirectory(), visitFile() etc to give control to programmer to do any specific task while traversing/visiting the file system. A concrete  implementation java.nio.file.SimpleFileVisitor has been provided those don't want to provide implementation for all of the methods from java.nio.file.FileVisitor.

Here is simple example using these new classes.

 

package com.test.jdk7;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.Files;
public class TestFileVisitor extends SimpleFileVisitor{
    private int nestedLavels = 0;
   
    public TestFileVisitor() {
        super();
    }
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
            throws IOException {
        System.out.println("");
        for(int i=0;i
            System.out.print(" ");
        System.out.println("- "+dir.getFileName());
        nestedLavels  = nestedLavels + 4 ;
        return super.preVisitDirectory(dir, attrs);
    }
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
            throws IOException {
        System.out.println("");
        for(int i=0;i
            System.out.print(" ");
        System.out.println("- "+file.getFileName());
        return super.visitFile(file, attrs);
    }
    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc)
            throws IOException {
        nestedLavels = nestedLavels - 4;
        return super.postVisitDirectory(dir, exc);
    }
   
    public static void main(String[] args) {
        Path startingPoint = Paths.get("/home/yogesh/root");
        try {
            //sarting the taversing
            Files.walkFileTree(startingPoint,new TestFileVisitor());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 

Comments

Popular posts from this blog

Composite Design Pattern by example

State Design Pattern by Example

Eclipse command framework core expression: Property tester