Traverse a Directory Structure Using Files.walkFileTree in Java NIO 2

By Arvind Rai, December 02, 2013
Java SE 7 has introduced many strong features for file handling. In Java NIO 2, we have the API that can traverse or walk the file tree. The class java.nio.file.Files has a method that is walkFileTree and an interface named java.nio.file. FileVisitor plays the role to traverse the directory structure. The complete file tree can be copied to another location and can be deleted as required.
Traverse a Directory Structure Using Files.walkFileTree in Java NIO 2

Role of FileVisitor to Traverse a Directory Structure

FileVisitor is an interface of java.nio.file. FileVisitor contains the method declaration that must be overridden to walk a file tree. We will understand the usability of all methods of FileVisitor. java.nio.file .SimpleFileVisitor is the class which implements FileVisitor and we can override its method to change the behavior.
postVisitDirectory(T dir, IOException exc)
postVisitDirectory() is invoked when all the child directory and files has been visited. This method is overridden for the purposes like deleting the file tree. The parent directory will be deleted only when the child file tree has been deleted. The Parameter T can be java.nio.file.Path which will contain the target directory.
preVisitDirectory(T dir, BasicFileAttributes attrs)
preVisitDirectory() is opposite to postVisitDirectory(). preVisitDirectory is invoked before going to child file tree or directory structure. preVisitDirectory will execute whatever we need do before traversing child. preVisitDirectory() can be used to copy the file tree from source to destination. T can be the object of java.nio.file.Path while copying the directory structure.
visitFile(T file, BasicFileAttributes attrs)
visitFile() is another generic method which can accept java.nio.file.Path object. visitFile() visits the file and will be invoked for copying and deleting both.
visitFileFailed(T file, IOException exc)
visitFileFailed() is invoked to handle error. While file visiting if there is any error then this method will execute and can be used for error logging which file has not been visited.

Files.walkFileTree in java.nio.file

Files.walkFileTree is the method that actually walks the file tree and invokes the FileVisitor methods as required. Two overloading methods are there to walk the tree. The difference between the two that we can assign maximum depth to walk the tree.
walkFileTree(Path startDir, FileVisitor<? super Path> visitor)

walkFileTree(Path startDir, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor)

Example to Copy Directory Structure Using Files.walkFileTree

We have taken two Path instance one for source and another for destination. We have directory structure of source which we will copy it to destination directory. It is returning FileVisitResult.CONTINUE which means that after executing this method, visit the child also.
WalkFileTreeCopyExample.java
package com.concretepage.io.file;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitOption;
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.EnumSet;
public class WalkFileTreeCopyExample  {
	public static void main(String[] args) throws IOException { 
		    final Path sourceDir = Paths.get("D:/cp/source");
			final Path targetDir = Paths.get("D:/cp/dest");
			Files.walkFileTree(sourceDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
		     new SimpleFileVisitor<Path>() {
		        @Override
		        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException  {
		            Path target = targetDir.resolve(sourceDir.relativize(dir));
		            try {
		                Files.copy(dir, target);
		            } catch (FileAlreadyExistsException e) {
		                 if (!Files.isDirectory(target))
		                     throw e;
		            }
		            return FileVisitResult.CONTINUE;
		        }
		        @Override
		        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
		            Files.copy(file, targetDir.resolve(sourceDir.relativize(file)));
		            return FileVisitResult.CONTINUE;
		        }
	    });
	
	}
}
 
preVisitDirectory() has been overridden to copy the directory from source to destination before traversing next directory. visitFile() has been overridden to copy the file from source to destination using Files.copy().

Example to Delete Directory Structure Using Files.walkFileTree

We have a directory and its child directory and files. We need to delete this file tree. We have assigned the parent directory path to Path variable.
WalkFileTreeDeleteExample.java
package com.concretepage.io.file;
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;
public class WalkFileTreeDeleteExample  {
	public static void main(String[] args) throws IOException {
		Path dirToDel = Paths.get("D:/cp");
		Files.walkFileTree(dirToDel, new SimpleFileVisitor<Path>() {
	        @Override
	        public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
	            if (e == null) {
	                Files.delete(dir);
	                return FileVisitResult.CONTINUE;
	            } else {
	            	System.out.println("Exception while iterating directory.");
	                throw e;
	            }
	        }
            @Override
	        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException{
	            Files.delete(file);
	            return FileVisitResult.CONTINUE;
	        }
	    });
		System.out.println("Directory Structure Deleted.");
	}
}
 
postVisitDirectory() has been overridden to delete the directory after traversing and deleting the child directory. visitFile() is deleting the file. Both the method is returning FileVisitResult.CONTINUE which means to continue the traversing and deleting.
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us