Last active
September 4, 2015 07:33
-
-
Save MrSoftwareEngineer/5ec4a49a679bc0de54a2 to your computer and use it in GitHub Desktop.
This sample makes filetree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Простой пример обхода всех директорий | |
* Пути файлов и директорий будут добавлены в лист и в конце выведены на консоль | |
* Для более тонкой настройки имеет смысл посмотреть другие методы класса | |
* 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