Java, Others

How to traverse files recursively in Java?

In this post you can find very use full program in Java.

Inorder to get this implementation you need to write a class extending SimpleFileVisitor<Path> . You can override the methods visitFilepreVisitDirectory method.

Function call Files.walkFileTree(Paths.get(ROOT), fileProcessor); Will take care of calling preVisitDirectory () first when ever it visits new directory & visitFile() method will be called successively.

You can write the custom actions to specific folder or any action to be done while visiting new directory. Its just simple example here to traverse the files path. You can convert the program into any requirement for Files

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;

/** Recursive listing with SimpleFileVisitor in JDK 7. */
public final class FileListingVisitor {

public static void main(String… aArgs) throws IOException{

String ROOT = “C:\\Root Folder”; // Set your root folder
FileVisitor<Path> fileProcessor = new ProcessFile();
Files.walkFileTree(Paths.get(ROOT), fileProcessor); // Will take care of calling preVisitDirectory & visitFile

}

}

class ProcessFile extends SimpleFileVisitor<Path> {

@Override
public FileVisitResult visitFile( Path aFile, BasicFileAttributes aAttrs ) throws IOException {

System.out.println(“Processing file:” + aFile);
return FileVisitResult.CONTINUE;

}

@Override public FileVisitResult preVisitDirectory( Path aDir, BasicFileAttributes aAttrs ) throws IOException {

System.out.println(“\n \n Processing directory:” + aDir + ” \n \n”);
return FileVisitResult.CONTINUE;

}

}

2 Comments

  1. Great goods from you, man. I’ve take into accout your
    stuff prior to and you are simply too great.
    I actually like what you’ve obtained here, really like what you are
    saying and the best way during which you are saying it. You’re
    making it entertaining and you continue to take care of to keep
    it sensible. I can not wait to learn much more from you.

    That is actually a tremendous web site.

Leave a Reply

Application By Sandeep G

en_USEnglish
en_USEnglish
%d bloggers like this:
Skip to toolbar