Starting with Java 7, you can use the file visitor template to recursively view the contents of a directory.
The documentation for the FileVisitor interface FileVisitor here .
This allows you to iterate over files without creating a large array of File objects.
A simple example for printing file names:
Path start = Paths.get(new URI("file:///my/folder/")); Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { System.out.println(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { System.out.println(dir); return FileVisitResult.CONTINUE; } else {
source share