Hey guys,
I constantly failed at this message : "The following information must be displayed on the console: "Total folders: [the number of folders in the directory and sub-directories]"."
However, I cannot understand where is the bug.
I once guessed whether it is because the request of getting total folders are : " [the number of folders in the directory and sub directories]" , so I explicitly changed my method in class `VisitFiles` visitFile() to explicitly check the file attribution `attr`, however, it still failed.
Any clue on where I might be wrong ?
package com.codegym.task.task31.task3113;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import static java.nio.file.FileVisitResult.CONTINUE;
/*
What's in the folder?
*/
public class Solution {
static long totalFolders = 0;
static long totalFiles = 0;
static long totalBytes = 0;
public static void main(String[] args) throws IOException {
// read the folder path from the console
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String folderPathName = reader.readLine();
Path folderPath = Paths.get(folderPathName);
// If the entered path is not a directory,
// display "[full path] is not a folder" and exit the program.
if (!Files.isDirectory(folderPath)) {
System.out.printf(folderPath.toAbsolutePath().toString() + " is not a folder");
return;
}
// walk file using self defined FileVIsitor
Files.walkFileTree(folderPath, new VisitFiles());
// display information
System.out.println("Total folders: " + (totalFolders));
System.out.println("Total files: " + totalFiles);
System.out.println("Total size: " + totalBytes);
}
// https://docs.oracle.com/javase/tutorial/essential/io/walk.html
//`FileVIsitor` specifies the required behavior in traversal ProcessBuilder
// The simple way is instead of implementing the `FileVisitor` iinterface,
// you can extend the `SimpleFileVisitor` class, which visits all files in a tree and throws an IOError
public static class VisitFiles extends SimpleFileVisitor<Path> {
// for each file
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr){
if (attr.isRegularFile()){
totalFiles += 1;
totalBytes += attr.size();
}
if (attr.isDirectory()){
totalFolders += 1;
}
return CONTINUE;
}
// for each directory
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException exc){
// only increase total folders once it had been visited
totalFolders += 1;
return CONTINUE;
}
// in case error accessing the file
// if you don't override this method and an error occurs
// default behavior is an IOException is thrown
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc){
System.err.println(exc);
return CONTINUE;
}
}
}