FileVisitor Interface Sample

Posted by

In this sample file visitor interface you can list all the folders and their regarding 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.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyFileVisitor implements FileVisitor<Path> {
private Map<String, List<String>> data = new HashMap<>();
private Map<String, IOException> exceptionData = new HashMap<>();

@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
final String folderName = file.getParent().toString();
final String fileName = file.getFileName().toString();
if (data.get(folderName) != null) {
data.get(folderName).add(fileName);
} else {
List<String> fileData = new ArrayList<>();
fileData.add(fileName);
data.put(folderName, fileData);
}
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
exceptionData.put(file.getFileName().toString(), exc);
return FileVisitResult.SKIP_SUBTREE;
}

@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}

public Map<String, List<String>> getData() {
return data;
}

public Map<String, IOException> getExceptionData() {
return exceptionData;
}

public static void main(String[] args) throws IOException {
Path path = Paths.get("c:/");
MyFileVisitor visitor = new MyFileVisitor();
Files.walkFileTree(path, visitor);
Map<String, List<String>> pathData = visitor.getData();
for (String obj : pathData.keySet()) {
System.out.println("+Folder: " + obj);
List<String> directoryFiles = pathData.get(obj);
for (String file : directoryFiles)
System.out.println("\t -File Name: " + file);
}
System.out.println("Exception Count: " + visitor.getExceptionData().size());
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *