The Files Class

Basic Java
≈ 2 min read

Files — high-level operations around Path

Path describes a path, while the Files class performs operations on that path: it creates files and directories, reads and writes data, copies, moves, deletes, and obtains file-system properties. It is a set of static methods, so there is no need to create a Files object.

Path path = Path.of("notes.txt");

Files.writeString(path, "Hello", StandardCharsets.UTF_8);
String text = Files.readString(path, StandardCharsets.UTF_8);

For a small text file, methods like these are often simpler than manually assembling a reader/writer chain. But convenience does not remove the question of size: methods that return the whole file as one string or array load all of its contents into memory.

Directories, copying, and moving

Path source = Path.of("data", "report.txt");
Path backup = Path.of("backup", "report.txt");

Files.createDirectories(backup.getParent());
Files.copy(source, backup);

createDirectories() creates missing directories along the path and does not require each parent to be created with a separate call. For copying and moving, behavior when the target file already exists is configured with options, such as StandardCopyOption.REPLACE_EXISTING.

Checks and metadata

Through Files, you can check a path's type and read file properties: for example isDirectory(), isRegularFile(), size(), and the last-modified time. However, the state of the file system can change between a check and the next operation.

exists() is not a guarantee of future success. A Files.exists(path) check describes the state at the moment of the call. The file may disappear or its permissions may change immediately afterward, so the operation itself must still handle failure correctly.

Methods that return a Stream

Some operations, such as Files.list() and Files.lines(), return a Stream connected to an open file-system resource. That stream must be closed after use.

try (Stream<Path> entries = Files.list(Path.of("data"))) {
    entries.forEach(System.out::println);
}