Sub topic 12
Creating and listing directories
This chapter covers creating directories and listing what they contain with java.nio.file. It assumes you know Path and Files.writeString, try-with-resources, checked exceptions, and Stream. It also assumes Java 11 or later. Recursive traversal is covered in a later chapter. Here the focus is a single directory level.
Creating one directory
Files.createDirectory(Path) creates exactly one directory. It is strict about its preconditions:
- If the parent directory does not exist, it throws
NoSuchFileException. - If anything already exists at the path, it throws
FileAlreadyExistsException. That includes a regular file and an existing directory.
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class CreateOne {
public static void main(String[] args) throws IOException {
Path dir = Path.of("demo-single", "inbox");
try {
Files.createDirectory(dir);
System.out.println("Created " + dir);
} catch (FileAlreadyExistsException e) {
System.out.println("Already exists: " + e.getFile());
} catch (NoSuchFileException e) {
System.out.println("Parent is missing: " + e.getFile());
}
}
}On a fresh machine this prints Parent is missing: demo-single/inbox, because demo-single does not exist yet. The strictness is useful when the directory must be new. For example, you can use it as a simple claim that only one process wins. The check and the creation happen in one operation, so no other process can slip in between them.
Creating a whole path
Files.createDirectories(Path) creates the directory and any missing parents. It does nothing if the directory already exists, so you can call it on every start-up.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class CreateMany {
public static void main(String[] args) throws IOException {
Path dir = Path.of("demo", "reports", "2026");
Path created = Files.createDirectories(dir);
System.out.println(created);
System.out.println(Files.isDirectory(created));
}
}The method returns the path it was given. Two edge cases still throw FileAlreadyExistsException:
- The final path exists but is a regular file.
- A parent component exists but is a regular file.
If you pass a symbolic link that points to a directory, the call succeeds.
You can pass FileAttribute values to both methods. On POSIX systems, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")) creates a private directory. On Windows the call throws UnsupportedOperationException, because that attribute type is not supported there.
Choosing a creation method
| Method | Creates parents | Existing directory | Typical use |
|---|---|---|---|
| `createDirectory` | No | Throws `FileAlreadyExistsException` | The directory must be new |
| `createDirectories` | Yes | Does nothing | Ensure a directory exists |
| `createTempDirectory` | No (the parent must exist) | Always a new, uniquely named directory | Scratch space for tests or work files |
Files.createTempDirectory(prefix) puts the directory in the default temporary location. Files.createTempDirectory(dir, prefix) puts it inside a directory you choose. The system does not delete temporary directories for you, so clean them up when you finish.
Listing a directory with Files.list
Files.list(Path) returns a Stream<Path> of the entries directly inside a directory. It does not descend into subdirectories. Each element is the directory path with the entry name resolved onto it. If you list demo/reports/2026, you get demo/reports/2026/a.txt, not a.txt. Call getFileName() when you need only the name.
The following program builds a small tree and lists it:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class ListDemo {
public static void main(String[] args) throws IOException {
Path dir = Path.of("demo", "reports", "2026");
Files.createDirectories(dir);
Files.writeString(dir.resolve("a.txt"), "a\n");
Files.writeString(dir.resolve("b.csv"), "b\n");
Files.createDirectories(dir.resolve("archive"));
try (Stream<Path> entries = Files.list(dir)) {
entries.sorted()
.forEach(p -> System.out.println(
(Files.isDirectory(p) ? "[dir] " : "[file] ")
+ p.getFileName()));
}
}
}The output is:
[dir] archive
[file] a.txt
[file] b.csvThree points matter here.
- Close the stream. The stream holds an open directory handle. Without try-with-resources you leak a file descriptor.
- The order is unspecified. The file system decides it, and it can differ between machines and runs. Call
sorted()whenever the order is visible to a user or a test.PathisComparable, so no comparator is needed. - The listing is lazy. Entries are read as the stream pulls them. A directory that changes during iteration may or may not show the new entries.
Listing with a glob using DirectoryStream
Files.newDirectoryStream(dir, glob) lists only the entries whose names match a glob pattern. It returns a DirectoryStream<Path>, which is Iterable and Closeable, so it works in a for-each loop.
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class GlobDemo {
public static void main(String[] args) throws IOException {
Path dir = Path.of("demo", "reports", "2026");
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, "*.{txt,csv}")) {
for (Path p : ds) {
System.out.println(p.getFileName());
}
}
}
}The glob is matched against the file name only, not the full path. In the pattern, * matches any characters within one name, ? matches one character, and {a,b} matches either alternative. A DirectoryStream can be iterated only once. Calling iterator() a second time throws IllegalStateException.
You can also pass a DirectoryStream.Filter<Path> when a glob is not enough. Its accept method may throw IOException, which makes it convenient for checks that touch the file system:
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class SubdirsOnly {
public static void main(String[] args) throws IOException {
Path dir = Path.of("demo", "reports", "2026");
DirectoryStream.Filter<Path> onlyDirs = Files::isDirectory;
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, onlyDirs)) {
ds.forEach(p -> System.out.println(p.getFileName()));
}
}
}Choosing between list and newDirectoryStream
| Question | `Files.list` | `Files.newDirectoryStream` |
|---|---|---|
| Return type | `Stream<Path>` | `DirectoryStream<Path>` (`Iterable`) |
| Filtering | Stream operations such as `filter` | Glob string or `Filter` object |
| Sorting, mapping, collecting | Built in through the Stream API | Copy into a list first |
| Iterations allowed | One | One |
| Runtime error wrapper | `UncheckedIOException` | `DirectoryIteratorException` |
Use Files.list when you want to chain stream operations. Use newDirectoryStream for a simple glob or when you prefer a plain loop. Both stay cheap on very large directories, because they do not load every entry up front.
Errors when listing
Opening a listing can throw checked exceptions, all subclasses of IOException:
NoSuchFileExceptionwhen the directory does not exist.NotDirectoryExceptionwhen the path is a regular file.AccessDeniedExceptionwhen you lack permission to read the directory.
Failures that happen after the listing has opened, for example the directory being removed mid-iteration, cannot be checked exceptions, because lambdas and iterators cannot declare them. Files.list wraps them in UncheckedIOException. A DirectoryStream iterator wraps them in DirectoryIteratorException. In both cases getCause() returns the original IOException.
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.util.stream.Stream;
public class SafeList {
public static void main(String[] args) {
Path dir = Path.of("demo", "reports", "2026");
try (Stream<Path> entries = Files.list(dir)) {
System.out.println(entries.count() + " entries");
} catch (NoSuchFileException e) {
System.out.println("No such directory: " + e.getFile());
} catch (NotDirectoryException e) {
System.out.println("Not a directory: " + e.getFile());
} catch (IOException e) {
System.out.println("Cannot open: " + e.getMessage());
} catch (UncheckedIOException e) {
System.out.println("Failed while reading: " + e.getCause().getMessage());
}
}
}The two specific catch clauses come before IOException because they are its subclasses. Reversing the order would not compile.
Common mistakes
- Forgetting to close the stream returned by
Files.list. On a long-running service this eventually exhausts file descriptors. - Assuming the listing is sorted. It often looks sorted on one machine and not on another.
- Expecting
Files.listto include nested files. It returns one level. UseFiles.walkfor the whole tree. - Using
createDirectoryfor a nested path such asa/b/cwhena/bis missing.
Exercise
A start-up routine must make sure the directory cache/images exists, then print the names of the .png and .jpg files in it in alphabetical order. Which methods would you use, and why must the listing be closed?
Show answer
Call Files.createDirectories(Path.of("cache", "images")). It creates cache if needed and does nothing if images already exists. For the listing, use Files.newDirectoryStream(dir, "*.{png,jpg}") and copy the names into a list, then sort it. Or use Files.list(dir) with filter on the file name and sorted(). The listing holds an open directory handle, so it must be closed with try-with-resources to avoid leaking a file descriptor. The order must be sorted explicitly because the file system does not guarantee it.
Exercise
What is the difference between NoSuchFileException and NotDirectoryException when you call Files.list, and which exception type signals a failure that happens while you are consuming the stream?
Show answer
NoSuchFileException means nothing exists at the path. NotDirectoryException means something exists but it is not a directory. Both are checked IOException subclasses thrown when the listing is opened. A failure during consumption is reported as an unchecked UncheckedIOException, whose getCause() is the original IOException.