FileVisitor - this is an interface that is implemented if you wanted to walk in a file tree.
Four requirements that needs implementation
1. preVisitDirectory() - called before all the directories entries are visited
2. postVisitDirectory() - called after all the directories entries are visited
3. visitFile() - call the file being visited
4. visitFileFailed() - called when the file cannot be accessed
Each process returned FileVisitor. You can control the walking through this returned values.
1. CONTINUE
2. TERMINATE
3. SKIP_SUBTREE
4. SKIP_SIBLINGS
SimpleFileVisitor - is a class which implements the FileVisitor interface. If you don't want to implement all the requirements, use this class.
Two methods to walk the file tree after implementing the file visitor
1. Files.walkFileTree(Path, FileVisitor)
2. Files.walkFileTree(Path, Set<FileVisitOption>, int, FileVisitor)
==================
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
public class Practice1 extends SimpleFileVisitor<Path> {
public static void main(String[] args) throws IOException {
Path thePath = Paths.get("README.md");
Practice1 obj = new Practice1();
BasicFileAttributes attributes = Files.readAttributes(thePath, BasicFileAttributes.class);
obj.visitFile(thePath, attributes);
System.out.println("Walking: " + Files.walkFileTree(thePath, obj));
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if(attrs.isRegularFile()){
System.out.println("The File " + file + " is a regular file.");
System.out.println("The size is " + attrs.size());
}else{
System.out.println("Note a regular file: " + file);
}
return FileVisitResult.TERMINATE;
}
}
==================
Result:
The File README.md is a regular file.
The size is 72
The File README.md is a regular file.
The size is 72
Walking: README.md
Note: I will continue updating this but not that much now since I will be focusing on Spring and Android.
YOU ARE READING
Java Programming
De Todohttps://docs.oracle.com/javase/tutorial/ This is the link where I learned my java lessons online. I choose java as first programming language. I am a career shifter. I just want to start something new. I choose to write it here in Wattpad so that I...