Ketterle
Ketterle

Reputation: 21

Printing directories tree to a .txt file using FileVisitor

I'm trying to print the whole directories tree to .txt file and I'm having some issues since my program is just printing the first file line only.

The code is:

package n1exercici3;

import java.io.*;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;

public class DirectorisAFitxer implements FileVisitor<Path> {

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        try {
            PrintWriter writer = new PrintWriter("directoris.txt");
            writer.append("D: "+dir+"\n");
            writer.close();
            return FileVisitResult.CONTINUE;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        try {

            PrintWriter writer = new PrintWriter("directoris.txt");
            writer.append("  F: "+file+"\n");
            writer.close();
            return FileVisitResult.CONTINUE;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        System.out.println("Invalid file!");
        return FileVisitResult.TERMINATE;    
    }



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

The file is properly created, so I guess the issues are related to the writer. Right now I'm trying with append() because write() method didn't work, but I'm having the very same outcome.

Upvotes: 0

Views: 82

Answers (1)

Thomas Behr
Thomas Behr

Reputation: 896

Since you are creating a new PrintWriter instance each time you visit a file, you are overwriting the contents of the existing file.

There are two ways to solve this:

  1. Create one PrintWriter instance and use that one instance for all your write operations. Only close this instance once your traversal is finished. This is the recommended way for use cases such as yours.

  2. Create PrintWriter instances that actually append what they write to their target files:

PrintWrtier writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream("directoris.txt", true)));

Upvotes: 0

Related Questions