Записать результаты работы Files.walkFileTree () в файл в формате «Tree» (Java)
Моя задача - вставить путь к каталогу в командную строку и записать результаты работы Files.walkFileTree () в файл в формате «Дерева». У меня такой код:
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...
и так далее ... Но что-то пошло не так ... Мне нужна помощь. Заранее спасибо!