Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 201 ยท Input and Output

Working with Directories

Work with folders in Java - create directories, list them with Files.list and DirectoryStream globs, walk and search trees, read file attributes, use temp folders and delete trees.

Files rarely live alone. A photo app scans a folder of pictures, a build tool finds every .java file under src, a backup script copies a whole tree, and a cleanup job deletes log files older than 30 days. All of these need to work with directories (folders): listing what's inside, walking through sub-folders, filtering by name, size or date, and creating or deleting whole trees.

The java.nio.file API from Reading and Writing Files handles this too. This lesson covers listing a folder with Files.list and DirectoryStream, walking trees with Files.walk and Files.find, glob patterns, file attributes such as size and modification time, temporary folders, deleting and copying trees with walkFileTree, and the legacy java.io.File class you'll meet in older code.

Every example builds a small sample project in a fresh temporary folder, so the output is the same each time you run it.

Creating directories

Files.createDirectory(path) creates exactly one folder: it fails if the folder exists (FileAlreadyExistsException) or if the parent is missing (NoSuchFileException). Files.createDirectories(path) creates all missing parents and quietly succeeds if the folder is already there, so it's what you want most of the time.

Java Creating folders and listing one level

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Files.createTempDirectory(prefix) makes a new folder with a unique name inside the system's temp directory (the java.io.tmpdir property) and is perfect for scratch work and tests. Files.list(dir) returns a Stream<Path> of the direct children only; it doesn't descend into assets.

Two habits from this example matter in real code:

  • Close the stream. Files.list keeps the directory open, so always use it in try-with-resources.
  • Sort if order matters. The operating system returns entries in no particular order, and the order differs between Windows, Linux and macOS. That's why the example calls sorted(). Paths sort by their text, character by character, so on Linux README.md (uppercase R) comes before assets.

DirectoryStream and glob patterns

Files.newDirectoryStream(dir, glob) lists a folder like Files.list, but filters names with a glob, the same wildcard syntax you use in a terminal. It returns an Iterable, so it works with a for-each loop:

Java Filtering a folder with globs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The glob syntax in a nutshell:

Pattern Matches
* any characters within one name (not across /)
** any characters, across folder boundaries (for paths, see below)
? exactly one character
{jpg,png} any of the comma-separated alternatives
[abc], [a-z] one character from the set or range

On Linux the match is case-sensitive, so *.jpg doesn't match beach.JPG; the last glob uses character sets to accept any case. On Windows, matching follows the file system and is case-insensitive. Note that *.jpg doesn't match draft.jpg.tmp: the pattern has to match the whole name.

Walking a whole tree

To include sub-folders, use Files.walk(start), which returns every path in the tree, depth-first, starting with start itself. An optional maxDepth limits how far it goes. Files.find(start, maxDepth, matcher) walks the same way but filters with a function that receives each path and its attributes, which is faster than calling Files.size or Files.isDirectory for every path yourself:

Java Walking, finding and summarizing a project

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notes on walking:

  • Files.walk and Files.find are lazy streams that hold open directory handles, so close them with try-with-resources, like Files.list.
  • A maxDepth of 1 means "the start folder and its direct children", 0 means just the start folder.
  • A PathMatcher from FileSystems.getDefault().getPathMatcher("glob:...") matches whole paths, where ** crosses folder boundaries: **/src/**.java means "a .java file anywhere below a src folder". Prefix regex: instead of glob: to use a regular expression.
  • By default the walk doesn't follow symbolic links, which protects you from endless loops. Pass FileVisitOption.FOLLOW_LINKS if you need to; Java then detects cycles and reports them with FileSystemLoopException.
  • If one folder can't be read (no permission), Files.walk fails with an UncheckedIOException in the middle of the stream. When that's a real possibility, use walkFileTree (below), which lets you skip the failing folder and keep going.
  • The lambda in summingLong has to catch IOException, because stream lambdas can't throw checked exceptions. Files.find avoids that problem since it hands you the attributes directly.

File attributes

Besides content, every file has metadata: its size, timestamps, whether it's a folder or a link, and OS-specific details like permissions. Files has quick methods for single attributes, and Files.readAttributes reads them all at once, which is much faster when you need several:

Java Size, timestamps and other attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • Files.size, getLastModifiedTime, isHidden, isSymbolicLink, isExecutable and getOwner read single attributes. setLastModifiedTime changes the timestamp, which is how tools like touch work.
  • FileTime converts to and from Instant with toInstant() and FileTime.from(instant), so you can compare it with the Dates and Times API.
  • BasicFileAttributes also has creationTime() and lastAccessTime(), but many file systems don't track them reliably (Linux often reports the modification time for both).
  • Platform-specific views like PosixFileAttributes (Linux/macOS permissions) and DosFileAttributes (Windows read-only/hidden flags) are available when the OS supports them. Check supportedFileAttributeViews() first, as the example does.

Deleting and copying whole trees

Files.delete only removes empty folders, and Files.copy copies a folder without its contents. For whole trees, use Files.walkFileTree with a FileVisitor. Its callbacks run before a folder is entered (preVisitDirectory), for each file (visitFile), after a folder's contents are done (postVisitDirectory) and when something can't be read (visitFileFailed). That's exactly what deletion needs, since a folder can only be deleted after everything in it:

Java Copying and deleting a tree with walkFileTree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

SimpleFileVisitor implements all four callbacks with "just continue" defaults, so you override only what you need. The return value steers the walk: CONTINUE, SKIP_SUBTREE (don't enter this folder), SKIP_SIBLINGS or TERMINATE. COPY_ATTRIBUTES keeps timestamps on the copies. Be careful with deleteTree: there's no recycle bin, and a wrong path deletes real data, so in real tools print what you would delete first, or require confirmation.

Temporary files and folders

Files.createTempFile(prefix, suffix) and Files.createTempDirectory(prefix) create uniquely named entries in the system temp folder; overloads accept a parent folder as the first argument, as the atomic save in Reading and Writing Files used. Java doesn't delete them automatically. Clean up yourself, usually in a finally block or after a test. file.toFile().deleteOnExit() exists, but it only works for files and empty folders, and every registration stays in memory until the JVM exits, so don't use it in long-running servers.

The legacy java.io.File class

Before Java 7, all of this was done with java.io.File. You'll still see it in older tutorials, libraries and APIs. It works, but its design makes errors easy to miss:

Java
File folder = new File("reports");
folder.mkdirs();                     // returns false on failure, but doesn't say why
File[] children = folder.listFiles(); // returns null if folder isn't a readable directory!
for (File f : children) {            // NullPointerException if the listing failed
    System.out.println(f.getName() + " " + f.length());
}
boolean gone = new File("old.log").delete();  // false: missing? locked? no permission?
java.io.File java.nio.file replacement Improvement
new File(name) Path.of(name) Immutable path type with resolve/relativize
file.exists(), length() Files.exists(p), Files.size(p) size throws if the file is missing instead of returning 0
file.mkdirs() Files.createDirectories(p) Throws a descriptive exception on failure
file.delete() Files.delete(p) Says why it failed
file.listFiles() Files.list(p), newDirectoryStream Throws instead of returning null; streams scale to huge folders
file.renameTo(other) Files.move(p, other) Works across disks, supports atomic moves

Convert between them with file.toPath() and path.toFile() when an older API requires a File.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A folder contains a.txt and a sub-folder sub with b.txt. What does Files.list(folder) return?

    Files.list returns the direct children only, files and folders alike. Use Files.walk to include the contents of sub-folders.
  2. 2. Which glob, used with newDirectoryStream, matches photo.png and photo.jpg but not photo.gif?

    Curly braces list alternatives in a glob. Square brackets match a single character from a set.
  3. 3. Why does deleteTree delete folders in postVisitDirectory rather than preVisitDirectory?

    Files.delete fails with DirectoryNotEmptyException on a non-empty folder. postVisitDirectory is called after every entry inside has been processed.
  4. 4. What is the main risk of forgetting try-with-resources around Files.walk(root)?

    Files.walk, list and find hold open directory handles until the stream is closed. Leaking them causes "too many open files" errors and, on Windows, locked folders.
  5. 5. new File("missing").listFiles() is called on a folder that doesn't exist. What happens?

    The legacy File API signals failure with null, which leads to NullPointerExceptions later. Files.list throws a descriptive exception instead.

Summary

  • Files.createDirectories creates a folder and any missing parents; createDirectory creates exactly one and fails if it exists.
  • Files.list streams a folder's direct children; newDirectoryStream(dir, glob) filters them with patterns like *.{jpg,png}. Sort results if order matters.
  • Files.walk (with an optional depth) and Files.find (with access to attributes) search entire trees; PathMatcher matches paths with glob: or regex:.
  • Always close list, walk and find streams with try-with-resources.
  • Files.size, getLastModifiedTime, readAttributes and friends read metadata; FileTime converts to Instant.
  • Files.walkFileTree with a SimpleFileVisitor copies and deletes whole trees, skipping folders with SKIP_SUBTREE; delete folders in postVisitDirectory.
  • Prefer Path/Files to the legacy File class, whose methods return false or null instead of explaining errors.

Next: Serialization, where you'll save whole Java objects to bytes and learn why that's both convenient and dangerous.