我正在尝试将整个目录树打印到 .txt 文件,但我遇到了一些问题,因为我的程序只打印了第一个文件行。
代码是:
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;
}
}
文件已正确创建,所以我想问题与作者有关。现在我正在尝试使用 append() 因为 write() 方法不起作用,但我得到了完全相同的结果。