Working with Directories in Java
A directory (or folder) holds files and other directories. NIO.2 handles directories with the same Files class: createDirectory and createDirectories make them, Files.list shows what's directly inside, Files.walk visits everything in the whole tree, and Files.find searches it. In this lesson, you will learn these methods and how to delete a folder with everything in it.
Methods
| Method | Description |
|---|---|
Files.createDirectory(dir) | It is used to create one folder; its parent must exist. |
Files.createDirectories(dir) | It creates the folder and any missing parents. |
Files.list(dir) | It returns a stream of the entries directly inside. |
Files.walk(dir) | It returns a stream of every entry in the tree, starting with dir. |
Files.walk(dir, depth) | It limits how many levels deep to go. |
Files.find(dir, depth, test) | It returns entries that match a test on path and attributes. |
Files.newDirectoryStream(dir, "*.txt") | It lists entries matching a glob pattern. |
The streams from list, walk and find keep folders open, so use them in try-with-resources. Their order isn't guaranteed, so sort when order matters.
Example: Building and Exploring a Tree
Let's see an example that creates a small folder tree and explores it.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class Tree {
public static void main(String[] args) throws IOException {
Path root = Path.of("school");
Files.createDirectories(root.resolve("class-a"));
Files.createDirectories(root.resolve("class-b"));
Files.writeString(root.resolve("rules.txt"), "Be kind");
Files.writeString(root.resolve("class-a/navika.txt"), "91");
Files.writeString(root.resolve("class-a/srihitha.txt"), "78");
Files.writeString(root.resolve("class-b/advitha.txt"), "85");
System.out.println("Directly inside school:");
try (Stream<Path> s = Files.list(root)) {
s.sorted().forEach(p -> System.out.println(" " + p.getFileName()
+ (Files.isDirectory(p) ? "/" : "")));
}
System.out.println("Every .txt file in the tree:");
try (Stream<Path> s = Files.walk(root)) {
s.filter(p -> p.toString().endsWith(".txt"))
.sorted()
.forEach(p -> System.out.println(" " + root.relativize(p)));
}
}
}Directly inside school:
class-a/
class-b/
rules.txt
Every .txt file in the tree:
class-a/navika.txt
class-a/srihitha.txt
class-b/advitha.txt
rules.txtExplanation: Files.list shows only the three entries directly inside school. Files.walk goes into every subfolder, so it also finds the files inside class-a and class-b. Both streams are sorted because the file system returns entries in no fixed order.
Example: Searching and Deleting a Tree
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.stream.Stream;
public class FindDelete {
public static void main(String[] args) throws IOException {
Path root = Path.of("photos");
Files.createDirectories(root.resolve("2026/nov"));
Files.write(root.resolve("2026/nov/big.jpg"), new byte[5000]);
Files.write(root.resolve("2026/small.jpg"), new byte[100]);
try (Stream<Path> found = Files.find(root, 10,
(p, attrs) -> attrs.isRegularFile() && attrs.size() > 1000)) {
found.forEach(p -> System.out.println("Large: " + p));
}
try (Stream<Path> all = Files.walk(root)) {
all.sorted(Comparator.reverseOrder()).forEach(p -> {
try {
Files.delete(p);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
System.out.println("photos exists? " + Files.exists(root));
}
}Large: photos/2026/nov/big.jpg
photos exists? falseExplanation: Files.find tests each entry's attributes, here keeping files over 1,000 bytes. To delete a whole tree, walk lists everything, and sorting in reverse order puts deeper paths before their parents, so each folder is empty by the time it's deleted.
Common Mistakes
Forgetting to close list or walk streams. Folder handles stay open.
Expecting list to include subfolder contents. Use walk.
Deleting a tree in walk order. Parents come first and can't be deleted while full; reverse the order.
Practice
- Easy: Print the names of all files in the current folder, sorted, with their sizes.
- Harder: Count the files and the total size of every
.javafile under a project folder, usingFiles.walk.
Key Takeaways
Was this tutorial helpful?