Skip to content

Instantly share code, notes, and snippets.

@MrSoftwareEngineer
Last active September 4, 2015 07:33
Show Gist options
  • Save MrSoftwareEngineer/5ec4a49a679bc0de54a2 to your computer and use it in GitHub Desktop.
Save MrSoftwareEngineer/5ec4a49a679bc0de54a2 to your computer and use it in GitHub Desktop.
This sample makes filetree
/*Простой пример обхода всех директорий
* Пути файлов и директорий будут добавлены в лист и в конце выведены на консоль
* Для более тонкой настройки имеет смысл посмотреть другие методы класса
* SimpleFileVisitor и переопределить их.
* Метод Files.walkFileTree имеет перегруженый аналог*/
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
public class WalkFileTreeSample {
public static void main(String[] args) {
final List<Path> filesAndDirs = new ArrayList<>();
Path root = Paths.get("/home");
SimpleFileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
filesAndDirs.add(file);
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
filesAndDirs.add(dir);
return super.preVisitDirectory(dir, attrs);
}
};
try {
Files.walkFileTree(root, fileVisitor);
} catch (IOException e) {
e.printStackTrace();
}
printList(filesAndDirs);
}
public static void printList(List<Path> list) {
for (Path path : list) {
System.out.println(path);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment