我的任务是在命令行中插入目录路径,并将 Files.walkFileTree() 操作的结果以“Tree”格式写入文件。我有以下代码:
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]
是路径“e://Music//Accept//”。要将结果写入我使用的文件中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;
}
}
计算文件夹,.relativize(dir)
我希望在文件中获得以下“树”结果:
|----接受
|----First album
|file...
|file...
|----Second album
|file...
等等...但是出了点问题...我需要帮助。先感谢您!