Sub topic 3
The Files class at a glance
This chapter gives you a map of java.nio.file.Files. It assumes you can write basic Java classes, use String, List and Stream, handle checked exceptions with try/catch, and run Java 11 or later. Later chapters cover each group of methods in detail. Here you learn how the class is organized, so you can find the right method quickly and predict how it behaves.
What Files is
Files is a final class that contains only static methods. You never create an instance. Each method takes one or more Path arguments and does the work. A Path only describes a location. Files is the class that touches the file system.
The split matters. Path operations such as resolve and normalize work on names alone and never fail because a file is missing. Almost every Files method asks the operating system for something, so it can fail. That is why most of them declare throws IOException.
The method families
The table groups the methods you will use most. The last column shows how much data each group holds in memory.
| Family | Typical methods | Memory use |
|---|---|---|
| Whole-file read | `readString`, `readAllLines`, `readAllBytes` | The entire file |
| Whole-file write | `writeString`, `write` | The entire content you pass in |
| Buffered I/O | `newBufferedReader`, `newBufferedWriter` | One buffer at a time |
| Lazy streams | `lines`, `list`, `walk`, `find` | Roughly one element at a time |
| Metadata | `exists`, `notExists`, `size`, `isDirectory`, `isRegularFile` | Small |
| Directories | `createDirectory`, `createDirectories`, `list` | Small |
| Copy, move, delete | `copy`, `move`, `delete`, `deleteIfExists` | Handled by the file system |
| Temporary files | `createTempFile`, `createTempDirectory` | Small |
Choose by size and shape of the data. A 2 KB configuration file belongs in readString. A 5 GB log should be read with lines or a buffered reader.
A short tour
This program uses several families together. It runs as shown and cleans up after itself.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class FilesTour {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("tour");
Path file = dir.resolve("hello.txt");
Files.writeString(file, "hello\n");
System.out.println(Files.exists(file));
System.out.println(Files.size(file));
System.out.println(Files.isDirectory(dir));
try (Stream<Path> children = Files.list(dir)) {
children.forEach(p -> System.out.println(p.getFileName()));
}
Files.delete(file);
Files.delete(dir);
}
}The output is true, 6, true and hello.txt. The size is 6 because the text is five letters plus one newline, all single-byte in UTF-8. Files.delete(dir) works only because the directory is empty by then.
Patterns shared by all methods
Once you know a few conventions, new methods are easy to guess.
Overloads with and without a charset
Every method that converts between bytes and text has two forms. One uses UTF-8. The other takes a Charset as an extra argument.
String a = Files.readString(file);
String b = Files.readString(file, StandardCharsets.ISO_8859_1);The Files methods that take no charset use UTF-8, not the platform default. That differs from older classes such as FileReader, which used the platform default before Java 18. The charsets chapter covers the details.
Options as varargs
Methods that open or copy files accept a trailing varargs list of options. The option type depends on the operation:
OpenOption(usuallyStandardOpenOption) for reading and writing, such asAPPEND.CopyOption(usuallyStandardCopyOption) forcopyandmove, such asREPLACE_EXISTING.LinkOptionfor metadata, such asNOFOLLOW_LINKS.FileVisitOptionfor tree walking, such asFOLLOW_LINKS.
You can pass no options and get the documented defaults. The defaults differ between operations. For example, Files.writeString truncates an existing file by default, while Files.copy refuses to overwrite one. Check the default before you rely on it.
Return values
Methods that write usually return the Path they were given. Files.writeString(file, "x") returns file, so you can chain calls. Files.createDirectories returns the directory path. Files.copy with two paths returns the target path. Methods that report a fact return a boolean, long or attribute object.
Links are followed by default
Metadata methods follow symbolic links unless you pass LinkOption.NOFOLLOW_LINKS. If link points to a directory, Files.isDirectory(link) returns true. With the option it returns false. Tree walking behaves the opposite way: it does not follow links unless you ask.
Methods that return streams must be closed
Files.lines, Files.list, Files.walk and Files.find return a Stream that holds an open file or directory handle. The stream releases the handle only when you close it. Put these calls in try-with-resources, as in the tour above. Leaving one open leaks a file descriptor. On Windows it can also stop you from deleting the file later.
Reading methods that return a collection, such as readAllLines, close the file before they return. You do not manage them.
Existence checks are only hints
Files.exists(path) and Files.notExists(path) are not opposites. Both return false when the answer cannot be determined, for example when a permissions problem prevents the check. Code that treats !exists as "the file is definitely absent" can be wrong.
There is also a timing problem. A file can appear or vanish between your check and your next call:
if (Files.exists(file)) {
String text = Files.readString(file); // may still throw NoSuchFileException
}Another process may delete the file in that gap. The reliable approach is to attempt the operation and handle the exception. Existence checks suit cases where a stale answer is harmless, such as choosing a message to show a user.
Failing loudly or quietly
Many operations come in pairs that differ in how they treat the "already so" case.
| Strict method | Lenient method | Difference |
|---|---|---|
| `delete` | `deleteIfExists` | `delete` throws `NoSuchFileException` for a missing file. The lenient one returns `false`. |
| `createDirectory` | `createDirectories` | `createDirectory` needs the parent to exist and throws `FileAlreadyExistsException` if the directory exists. `createDirectories` creates missing parents and accepts an existing directory. |
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class DeleteDemo {
public static void main(String[] args) throws IOException {
Path ghost = Path.of("does-not-exist.txt");
System.out.println(Files.deleteIfExists(ghost));
try {
Files.delete(ghost);
} catch (NoSuchFileException e) {
System.out.println("Missing: " + e.getFile());
}
}
}This prints false, then Missing: does-not-exist.txt. Use the strict form when a missing file means a bug in your program. Use the lenient form when you only want the file gone.
Working with relative paths
A relative Path is resolved against the JVM's current working directory, which is usually the directory you started the program in. Files never searches elsewhere. If Files.readString(Path.of("data.txt")) throws NoSuchFileException, print path.toAbsolutePath() first. The path often points somewhere other than you expected, especially when the program runs from an IDE or a build tool.
Choosing a starting method
- For a small text file, start with
readStringorwriteString. - For text that may be large, use
newBufferedReader,newBufferedWriterorlines. - For a question about a file, use a metadata method such as
sizeorisRegularFile. - For directories, start with
createDirectories,listorwalk. - For moving data around, use
copy,moveanddelete.
Exercise
A colleague writes if (Files.notExists(path)) { Files.createFile(path); } to create a file safely. Give two reasons this can still fail, and name a better approach.
Show answer
First, notExists returns false when existence cannot be determined, so the check may skip the creation even though the file is absent. Second, another process can create the file between the check and createFile, which then throws FileAlreadyExistsException. A better approach is to call Files.createFile(path) directly and catch FileAlreadyExistsException if the file existing is acceptable. Alternatively, open the file with StandardOpenOption.CREATE so the operation is one step.
Exercise
Why must Files.lines(file) be used inside try-with-resources, while Files.readAllLines(file) need not be?
Show answer
Files.lines returns a lazy stream that keeps the file open until the stream is closed, so skipping the close leaks a file handle. Files.readAllLines reads the whole file into a List and closes the file before it returns.