Write the results of Files.walkFileTree () operation to the file in "Tree" format (Java)

197 Views Asked by At

My task is to insert the directory path to the command line and write the results of Files.walkFileTree () operation to the file in "Tree" format. I have the following code:

public class IOTask {
public static void main(String[] args) {
        File file = new File(args[0]);
        if (file.exists() && file.isDirectory()) {
            Path files = Paths.get(args[0]);
            PrintFiles pf = new PrintFiles();
            try {
                Files.walkFileTree(files, pf);
            } catch (IOException e) {
                e.printStackTrace();
            }

Args [0] is the path "e://Music//Accept//". To write the results to the file I use FileVisitor.

public class PrintFiles extends SimpleFileVisitor<Path> {
private FileOutputStream outputStream;
private final Path baseFolder = Paths.get("e://Music//Accept//");

public PrintFiles() {
    try {
        this.outputStream = new FileOutputStream("data/File.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
    Path relative = baseFolder.relativize(dir);
    int count = relative.getNameCount();
    try {
        this.outputStream.write("|-----\t".repeat(count) + dir.getFileName() + System.getProperty("line.separator"));
    } catch (IOException | NumberFormatException e) {
        e.printStackTrace();
    }
    return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
    Path relative = baseFolder.relativize(file);
    int count = relative.getNameCount();
    if  (attr.isRegularFile()) {
        try {
            this.outputStream.write("|\t".repeat(count) + file.getFileName() + System.getProperty("line.separator"));
        } catch (IOException | NumberFormatException e) {
            e.printStackTrace();
        }
    }
    return FileVisitResult.CONTINUE;
}

}

Counting the folders with .relativize(dir) I expect to obtain the following "Tree" result in the file:

|----Accept

 |----First album

      |file...
      |file...

 |----Second album

      |file...

and so on... But something goes wrong... I need help. Thank you in advance!

0

There are 0 best solutions below