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.