In Java, java.nio.file.Files is a final class made only of static methods for files and directories. It arrived in Java 7 with the "NIO.2" file API. A Path says where something is; Files does the work: createFile(), copy(), move(), delete(), exists(), readAllLines(), write(), list(), walk(), and many more.
You never write new Files(). Import the class and call the methods on its name. Almost every method declares throws IOException, so main either declares it too or catches it. The Files Methods index lists all 50 guides.
Results can depend on the operating system.
Permissions, hidden files, symbolic links, and owners behave differently on Windows, macOS, and Linux. Method pages label outputs that are not the same everywhere.
Syntax
Java Syntax
Import Files and Path, build a path, and call static methods with it:
Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path dir = Paths.get("data"); // Java 7+; Path.of("data") on Java 11+
Files.createDirectories(dir); // make the folder if needed
Path file = dir.resolve("hello.txt"); // data/hello.txt
Files.write(file, "Hi!".getBytes("UTF-8")); // write 3 bytes
System.out.println(Files.size(file)); // 3
Reference
Files vs the Old java.io.File
java.io.File has existed since Java 1.0. Files plus Path is the modern replacement:
Convert between them with file.toPath() and path.toFile().
Concept
Working with Path
A java.nio.file.Path is just a name, like a street address: creating one never touches the disk. Get one with Paths.get("a", "b.txt") (Java 7+) or Path.of("a", "b.txt") (Java 11+), and combine paths with dir.resolve("b.txt"). getFileName() returns the last part, getParent() the folder, and dir.relativize(file) the part of file below dir. Windows prints \ between names and other systems print /, which is why the examples print relativize(...).toString().replace('\\', '/').
Reference
Exceptions You Will Meet
All of these live in java.nio.file and extend FileSystemException, which extends java.io.IOException:
Exception
Typical cause
NoSuchFileException
The file or a parent folder is missing, e.g. delete() or size()
lines(), list(), walk(), and find() return a lazy Stream, and newDirectoryStream() returns a DirectoryStream. Each keeps a file or folder open until it is closed, so always write try (Stream<Path> s = Files.list(dir)) { ... }. Because they read lazily, an I/O problem in the middle of the stream arrives as an unchecked UncheckedIOException. Directory entries come back in no particular order, so sort them when the order matters.
Pattern
The Temp-Folder Pattern
To experiment safely, create a scratch folder with createTempDirectory(), build every path with dir.resolve(...), and delete what you made in a finally block: files first, then folders (see deleteIfExists()). Print getFileName() or relative paths, never the full temp path, because its random name and location change on every run and every computer.
Code
Java Examples
Example 1 — Save a Shopping List and Read It Back
Write three lines into a file inside a temporary folder, read them back as a List, and remove both the file and the folder at the end.
Run with java FilesHubRoundTrip. The output is the same on Windows, macOS, and Linux.
File: shopping.txt
Items: [bread, apples, tea]
Second item: apples
How It Works
A private playground.Files.createTempDirectory("demo") makes a new, empty folder with a unique name under the system temp location, so the program never touches your real files.
Build the path, then use it.dir.resolve("shopping.txt") only joins names; nothing exists on disk until Files.write creates the file and writes each list element as one line.
Read it back.Files.readAllLines splits the content at the line breaks and returns the three items, so items.get(1) is apples.
Always tidy up. The finally block deletes the file and then the now-empty folder, even if reading had failed.
Example 2 — List a Folder in a Predictable Order
Create a few entries, then list the folder with Files.list inside try-with-resources. The names are sorted before printing because the operating system may return them in any order.
Run with java FilesHubListing. The output is the same on Windows, macOS, and Linux.
[budget.csv, photos/, todo.txt]
Cleaned up: true
How It Works
Three kinds of setup.createDirectory adds a subfolder and createFile adds two empty files; each call returns the Path it created, which is kept for the cleanup later.
A stream that must be closed.Files.list holds an open directory handle, so it sits in a try-with-resources header and is closed as soon as the names are collected.
Mark folders, then sort. Each entry becomes its file name plus a trailing slash for directories, and sorted() puts the strings in alphabetical order so every system prints the same line.
Delete inside-out. The two files and the subfolder go first, because Files.delete refuses to remove a folder that still has entries; notExists then confirms the temp folder is gone.
Example 3 — Catch the Specific Exceptions Files Throws
Trigger three common failures on purpose and catch each one by its own exception class. All of them extend IOException.
Java
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class FilesHubErrors {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path report = Files.createFile(dir.resolve("report.txt"));
try {
Files.createFile(report);
} catch (FileAlreadyExistsException e) {
System.out.println("createFile: report.txt is already there");
}
try {
Files.delete(dir.resolve("missing.txt"));
} catch (NoSuchFileException e) {
System.out.println("delete: missing.txt was not found");
}
try {
Files.delete(dir);
} catch (DirectoryNotEmptyException e) {
System.out.println("delete: the folder still contains report.txt");
}
Files.delete(report);
Files.delete(dir);
System.out.println("Done");
}
}
Output
Run with java FilesHubErrors. The output is the same on Windows, macOS, and Linux.
createFile: report.txt is already there
delete: missing.txt was not found
delete: the folder still contains report.txt
Done
How It Works
Create twice. The second createFile on the same path fails with FileAlreadyExistsException; the existing file is left untouched.
Delete something absent.Files.delete on a name that was never created throws NoSuchFileException. Use deleteIfExists when a missing file is fine.
Delete a full folder. The temp folder still holds report.txt, so deleting it throws DirectoryNotEmptyException instead of silently removing the contents.
Specific first, general later. Each catch names one subclass of IOException, so the program can react differently to each problem; anything unexpected still escapes through throws IOException.
A final utility class, added in Java 7 as part of NIO.2, with only static methods for working with files and directories: creating, copying, moving, deleting, checking, reading, writing, listing, and reading or changing attributes.
Prefer Files with Path for new code. Many java.io.File methods just return false when something fails, while Files throws specific exceptions such as NoSuchFileException.
They do the same thing. Paths.get works on Java 7 and later; Path.of was added in Java 11. The examples here use Paths.get or Files.createTempDirectory so they compile on Java 8.
Those streams keep a directory handle open. Put them in try-with-resources; otherwise the handle may leak, and on Windows it can stop you from deleting the folder.
Yes for the overloads without a Charset parameter, such as readAllLines(path), lines(path), and write(path, lines) from Java 8, and readString and writeString from Java 11. The Java 7 overloads take an explicit Charset.