Java Path and Files API
Java 7 introduced java.nio.file: a Path names a location, and the Files class performs every operation on it, reporting failures with specific exceptions. This page explains how the API is put together, runs each common operation, and shows the traps: name-based comparisons, path traversal, lost timestamps on copy and the cost of asking for attributes one at a time.
Contents
How the Path and Files API is put together
Before Java 7, all file work went through java.io.Filedelete()renameTo()falselistFiles()java.nio.file
is an interface for a location: a root such asPath or/ and a sequence of names. Creating and combining paths is pure string work and never touches the disk.C:\ is a class of static methods that do the work: create, read, write, copy, move, delete, list and read attributes. Each failure is a specificFiles subclass, such asIOException orNoSuchFileException .DirectoryNotEmptyException- Every
belongs to aPath , and each file system has aFileSystem thatFileSystemProvider delegates to. The default one is the operating system's disk, but the JDK also ships a ZIP file system, so the sameFiles calls work inside a ZIP archive; seeFilesZIP and GZIP .
| Type | Since | Role |
|---|---|---|
Path | Java 7 | A location; methods such as resolverelativizenormalize |
Paths.get | Java 7 | Creates a path; still works, but no longer recommended |
Path.of | Java 11 | Creates a path; the preferred factory |
Files | Java 7 | All operations on files and directories |
FileSystemsFileSystem | Java 7 | The default file system, ZIP file systems, path matchers |
Attribute views (BasicFileAttributesPosixFileAttributes | Java 7 | Metadata such as size, times, owner and permissions |
Files.readStringwriteString | Java 11 | Whole text files in one call |
Files.mismatch | Java 12 | Compares two files byte by byte |
All programs below were compiled and run on JDK 21 on Linux. Paths are printed with /
Building and taking apart paths
The program takes apart one deep path and combines it with others. None of these files exist, which shows that all Path
import java.nio.file.Path;
public class PathOps {
public static void main(String[] args) {
// A Path is just a name: nothing here touches the disk
Path report = Path.of("/home/ana/projects/app/reports/2026/q1.csv");
System.out.println("fileName: " + report.getFileName());
System.out.println("parent: " + report.getParent());
System.out.println("root: " + report.getRoot());
System.out.println("nameCount: " + report.getNameCount());
System.out.println("subpath: " + report.subpath(3, 5));
Path app = Path.of("/home/ana/projects/app");
System.out.println("resolve: " + app.resolve("config/app.properties"));
System.out.println("resolve /: " + app.resolve("/etc/hosts"));
System.out.println("sibling: " + report.resolveSibling("q2.csv"));
System.out.println("relativize: " + app.relativize(report));
System.out.println("back up: " + report.relativize(app));
Path messy = Path.of("/home/ana/./projects/app/../lib/util.jar");
System.out.println("normalize: " + messy.normalize());
// startsWith compares whole name elements, not characters
System.out.println("path startsWith \"/home/an\": " + report.startsWith("/home/an"));
System.out.println("string startsWith \"/home/an\": "
+ report.toString().startsWith("/home/an"));
Path relative = Path.of("reports", "q1.csv");
System.out.println("isAbsolute: " + relative.isAbsolute() + " for " + relative);
}
}
Output (on Linux):
fileName: q1.csv
parent: /home/ana/projects/app/reports/2026
root: /
nameCount: 7
subpath: app/reports
resolve: /home/ana/projects/app/config/app.properties
resolve /: /etc/hosts
sibling: /home/ana/projects/app/reports/2026/q2.csv
relativize: reports/2026/q1.csv
back up: ../../..
normalize: /home/ana/projects/lib/util.jar
path startsWith "/home/an": false
string startsWith "/home/an": true
isAbsolute: false for reports/q1.csv
| Method | Result |
|---|---|
getFileNamegetParentgetRoot | The last name, everything before it, and / |
getNameCountsubpath(3, 5) | 7 names (the root is not counted); names 3 and 4, counting from 0 |
resolve(other) | Appends a relative path; an absolute argument replaces the whole path, as /etc/hosts |
resolveSibling | Replaces the file name, keeping the directory |
relativize | The relative path from one location to another, in either direction |
normalize | Removes .dir/.. |
The two startsWithPath.startsWith/home/ana/.../home/an
Traps: equality, endsWith, traversal and links
Because a Path
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class PathTraps {
// Accepts a user-supplied name only if it stays inside the upload directory
static Path safeResolve(Path uploads, String userName) {
Path target = uploads.resolve(userName).normalize();
if (!target.startsWith(uploads)) {
throw new IllegalArgumentException("outside the upload directory: " + userName);
}
return target;
}
public static void main(String[] args) throws IOException {
// equals compares names, not files
Path a = Path.of("data/../report.txt");
Path b = Path.of("report.txt");
System.out.println("equals: " + a.equals(b));
System.out.println("equals after normalize: " + a.normalize().equals(b));
// endsWith also compares whole names
Path csv = Path.of("exports/q1.csv");
System.out.println("path endsWith \"csv\": " + csv.endsWith("csv"));
System.out.println("path endsWith \"q1.csv\": " + csv.endsWith("q1.csv"));
System.out.println("name endsWith \".csv\": "
+ csv.getFileName().toString().endsWith(".csv"));
// relativize needs two paths of the same kind
try {
Path.of("/srv/app").relativize(Path.of("logs"));
} catch (IllegalArgumentException e) {
System.out.println("relativize absolute vs relative: " + e.getMessage());
}
// Path traversal: normalize first, then check with Path.startsWith
Path uploads = Path.of("/srv/uploads");
for (String name : new String[] {"photo.png", "2026/cv.pdf", "../../etc/passwd",
"/etc/passwd"}) {
try {
System.out.println("accepted: " + safeResolve(uploads, name));
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
// A symbolic link: same file, different names
Path dir = Files.createTempDirectory("traps");
Path real = Files.writeString(dir.resolve("real.txt"), "x");
Path link = Files.createSymbolicLink(dir.resolve("link.txt"), real);
System.out.println("link equals real: " + link.equals(real));
System.out.println("Files.isSameFile: " + Files.isSameFile(link, real));
System.out.println("toRealPath of link: " + dir.relativize(link.toRealPath()));
try {
dir.resolve("missing.txt").toRealPath();
} catch (IOException e) {
System.out.println("toRealPath of missing: " + e.getClass().getSimpleName());
}
Files.delete(link);
Files.delete(real);
Files.delete(dir);
}
}
Output:
equals: false
equals after normalize: true
path endsWith "csv": false
path endsWith "q1.csv": true
name endsWith ".csv": true
relativize absolute vs relative: 'other' is different type of Path
accepted: /srv/uploads/photo.png
accepted: /srv/uploads/2026/cv.pdf
rejected: outside the upload directory: ../../etc/passwd
rejected: outside the upload directory: /etc/passwd
link equals real: false
Files.isSameFile: true
toRealPath of link: real.txt
toRealPath of missing: NoSuchFileException
anddata/../report.txt are notreport.txt , even though they usually name the same file. Afterequals they are. Normalize before putting paths in a set or a map key.normalize isendsWith("csv") forfalse , becauseq1.csv compares whole names. To check an extension, convert the file name to a string first.Path.endsWith between an absolute and a relative path throwsrelativize . CallIllegalArgumentException on both first.toAbsolutePath()- Path traversal:
points outside the upload directory, anduploads.resolve("../../etc/passwd") replaces it completely. Normalizing and then checking withresolve("/etc/passwd") rejected both and accepted the two legitimate names. WithoutPath.startsWith , thenormalize version would pass the check, because its first names are.. ./srv/uploads - A symbolic link and its target are different names, so
isequals , butfalse asks the file system and returnsFiles.isSameFile .true resolves all links and gives the real location. It fails withtoRealPath() for a missing file, so it doubles as an existence check. When links can point outside a directory, check the result ofNoSuchFileException rather thantoRealPath() .normalize()
Creating, copying, moving and deleting
The Files
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
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;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
public class FilesOps {
public static void main(String[] args) throws IOException {
Path root = Files.createTempDirectory("files-demo");
Path docs = Files.createDirectories(root.resolve("docs/drafts"));
Path draft = Files.writeString(docs.resolve("plan.txt"), "version 1");
Files.setLastModifiedTime(draft, FileTime.from(Instant.parse("2026-01-15T10:30:00Z")));
System.out.println("exists: " + Files.exists(draft) + ", regular file: "
+ Files.isRegularFile(draft) + ", directory: " + Files.isDirectory(docs));
System.out.println("createDirectories again (already there): "
+ root.relativize(Files.createDirectories(docs)));
try {
Files.createDirectory(docs);
} catch (FileAlreadyExistsException e) {
System.out.println("createDirectory again: FileAlreadyExistsException");
}
// copy refuses to overwrite unless told to
Path copy = root.resolve("docs/plan-copy.txt");
Files.copy(draft, copy);
System.out.println("plain copy keeps the time? "
+ Files.getLastModifiedTime(copy).equals(Files.getLastModifiedTime(draft)));
try {
Files.copy(draft, copy);
} catch (FileAlreadyExistsException e) {
System.out.println("second copy: FileAlreadyExistsException");
}
Files.copy(draft, copy, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
System.out.println("COPY_ATTRIBUTES keeps the time? "
+ Files.getLastModifiedTime(copy).equals(Files.getLastModifiedTime(draft)));
// copy from a stream, for example a download or an upload
long n = Files.copy(new ByteArrayInputStream("uploaded".getBytes(StandardCharsets.UTF_8)),
root.resolve("upload.bin"));
System.out.println("copied " + n + " bytes from an InputStream");
// move renames, or moves to another directory
Path published = Files.move(draft, root.resolve("docs/plan-final.txt"),
StandardCopyOption.ATOMIC_MOVE);
System.out.println("after ATOMIC_MOVE, old name exists: " + Files.exists(draft)
+ ", new name: " + root.relativize(published));
try {
Files.move(draft, root.resolve("x.txt"));
} catch (NoSuchFileException e) {
System.out.println("move a missing file: NoSuchFileException");
}
// Compare content without reading both files yourself (Java 12+)
System.out.println("mismatch(copy, published): " + Files.mismatch(copy, published));
Files.writeString(copy, "version 2");
System.out.println("mismatch after change: " + Files.mismatch(copy, published));
// delete only removes empty directories
try {
Files.delete(root.resolve("docs"));
} catch (DirectoryNotEmptyException e) {
System.out.println("delete non-empty directory: DirectoryNotEmptyException");
}
System.out.println("deleteIfExists on missing file: "
+ Files.deleteIfExists(root.resolve("nope.txt")));
for (Path p : new Path[] {copy, published, root.resolve("upload.bin"), docs,
docs.getParent(), root}) {
Files.delete(p);
}
System.out.println("cleaned up: " + Files.notExists(root));
}
}
Output:
exists: true, regular file: true, directory: true
createDirectories again (already there): docs/drafts
createDirectory again: FileAlreadyExistsException
plain copy keeps the time? false
second copy: FileAlreadyExistsException
COPY_ATTRIBUTES keeps the time? true
copied 8 bytes from an InputStream
after ATOMIC_MOVE, old name exists: false, new name: docs/plan-final.txt
move a missing file: NoSuchFileException
mismatch(copy, published): -1
mismatch after change: 8
delete non-empty directory: DirectoryNotEmptyException
deleteIfExists on missing file: false
cleaned up: true
createdcreateDirectories anddocs in one call, and calling it again did nothing.docs/drafts , for a single level, throwscreateDirectory instead.FileAlreadyExistsException- A plain
does not keep the modification time: the copy got the current time.copy copies the timestamps and, where possible, the permissions. Backup and sync tools that compare times need it.COPY_ATTRIBUTES refuses to overwrite and throwscopy ;FileAlreadyExistsException allows it.REPLACE_EXISTING saves a stream straight to a file and returns the byte count, 8 here.Files.copy(InputStream, Path) renames within a directory or moves between directories. Withmove the rename is a single file system operation: other programs see either the old name or the new one. It throwsATOMIC_MOVE when that is impossible, such as between two disks. Without it, a move between file systems is a copy followed by a delete.AtomicMoveNotSupportedException returned -1 for identical files and 8 after the change, the index of the first differing byte: "version 1" and "version 2" differ at their ninth character.Files.mismatch fails withdelete on a directory that still has content; deleting a tree needs a walk, shown inDirectoryNotEmptyExceptionFiles.walk and DirectoryStream . returnsdeleteIfExists instead of throwing when there is nothing to delete.false
Checking Files.existsexistsnotExistsfalse
File attributes and file stores
Metadata is grouped into views. The basicposixacldos
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;
import java.time.Instant;
import java.util.Map;
import java.util.TreeMap;
public class Attributes {
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("attrs", ".txt");
Files.writeString(file, "twelve bytes");
System.out.println("supported views: "
+ new java.util.TreeSet<>(file.getFileSystem().supportedFileAttributeViews()));
// Read many attributes in one call instead of one call per attribute
BasicFileAttributes a = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("size: " + a.size() + ", regular: " + a.isRegularFile()
+ ", directory: " + a.isDirectory() + ", symlink: " + a.isSymbolicLink());
Files.setLastModifiedTime(file, FileTime.from(Instant.parse("2026-01-15T10:30:00Z")));
System.out.println("last modified: " + Files.getLastModifiedTime(file));
// POSIX permissions (Linux and macOS); Windows uses ACLs instead
if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
PosixFileAttributes px = Files.readAttributes(file, PosixFileAttributes.class);
System.out.println("temp file permissions: "
+ PosixFilePermissions.toString(px.permissions())
+ ", owner is a user principal: " + (px.owner() != null));
Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rw-r-----"));
System.out.println("after change: "
+ PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));
// The string form: "view:name" or "view:*"
Map<String, Object> some = new TreeMap<>(Files.readAttributes(file,
"posix:size,isRegularFile,lastModifiedTime"));
System.out.println("readAttributes(\"posix:...\"): " + some);
}
FileStore store = Files.getFileStore(file);
System.out.println("file store has usable space: " + (store.getUsableSpace() > 0)
+ ", supports posix: " + store.supportsFileAttributeView("posix"));
Files.delete(file);
}
}
Output (on Linux):
supported views: [basic, dos, owner, posix, unix, user]
size: 12, regular: true, directory: false, symlink: false
last modified: 2026-01-15T10:30:00Z
temp file permissions: rw-------, owner is a user principal: true
after change: rw-r-----
readAttributes("posix:..."): {isRegularFile=true, lastModifiedTime=2026-01-15T10:30:00Z, size=12}
file store has usable space: true, supports posix: true
- This Linux file system supports six views.
adds fields such as the inode number andunix is emulated with extended attributes; neither is available everywhere, so portable code sticks todos and checks before using the others.basic creates files readable only by the owner (createTempFile ) on POSIX systems, a safe default for temporary data.rw------- adds read access for the group.rw-r------ The string form
returns a map of just those attributes, which is handy for generic tools. The typed form,"posix:size,isRegularFile,lastModifiedTime" , is checked by the compiler and is the better choice in normal code.readAttributes(file, PosixFileAttributes.class) describes the volume the file is on: free and usable space, and which attribute views it supports.Files.getFileStore
Reading attributes one at a time versus together
Each of Files.isRegularFileFiles.sizeFiles.getLastModifiedTimereadAttributes
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.stream.Stream;
public class AttributeSpeed {
interface Scan {
long run(List<Path> files) throws IOException;
}
// Three questions, three file system calls per file
static long separateCalls(List<Path> files) throws IOException {
long total = 0;
for (Path p : files) {
if (Files.isRegularFile(p)) {
total += Files.size(p);
Files.getLastModifiedTime(p);
}
}
return total;
}
// One call per file returns all basic attributes together
static long oneCall(List<Path> files) throws IOException {
long total = 0;
for (Path p : files) {
BasicFileAttributes a = Files.readAttributes(p, BasicFileAttributes.class);
if (a.isRegularFile()) {
total += a.size();
a.lastModifiedTime();
}
}
return total;
}
static long legacyFile(List<Path> files) {
long total = 0;
for (Path p : files) {
File f = p.toFile();
if (f.isFile()) {
total += f.length();
f.lastModified();
}
}
return total;
}
static void measure(String label, List<Path> files, Scan scan) throws IOException {
long best = Long.MAX_VALUE;
long total = 0;
for (int i = 0; i < 5; i++) {
long start = System.nanoTime();
total = scan.run(files);
best = Math.min(best, System.nanoTime() - start);
}
System.out.printf("%-42s %4d ms total size %,d bytes%n", label, best / 1000000,
total);
}
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("many-files");
for (int i = 0; i < 20000; i++) {
Files.writeString(dir.resolve("file-" + i + ".txt"), "x".repeat(i % 100));
}
List<Path> files;
try (Stream<Path> s = Files.list(dir)) {
files = s.toList();
}
System.out.println(files.size() + " files, best of 5 runs");
separateCalls(files); // warm-up
measure("isRegularFile + size + getLastModifiedTime", files,
AttributeSpeed::separateCalls);
measure("readAttributes(BasicFileAttributes)", files, AttributeSpeed::oneCall);
measure("java.io.File isFile + length + lastModified", files,
AttributeSpeed::legacyFile);
for (Path p : files) {
Files.delete(p);
}
Files.delete(dir);
}
}
Output (rough comparison on a 2-CPU Linux VM, JDK 21, best of 5; absolute times will differ on yours):
20000 files, best of 5 runs
isRegularFile + size + getLastModifiedTime 44 ms total size 990,000 bytes
readAttributes(BasicFileAttributes) 23 ms total size 990,000 bytes
java.io.File isFile + length + lastModified 40 ms total size 990,000 bytes
All three found the same total of 990,000 bytes. The separate calls made three statreadAttributesjava.io.FileFiles.walkFileTree
Moving from java.io.File
Filefile.toPath()path.toFile()PathFiles
java.io.File | NIO.2 | What improves |
|---|---|---|
new File(path) | Path.of(path) | Works with any file system, including ZIP |
file.delete() | Files.delete(path) | An exception says why instead of false |
file.renameTo(dest) | Files.move(path, dest) | Options for replacing and atomic moves |
file.mkdirs() | Files.createDirectories(path) | An exception on failure |
file.listFiles() | Files.list(dir)Files.newDirectoryStream(dir) | Lazy; does not load a huge directory at once |
file.length()lastModified() | Files.readAttributes | All attributes in one call |
file.exists() | Files.exists(path) | Can tell "missing" apart from "unknown" with notExists |
File.createTempFile | Files.createTempFile | Owner-only permissions on POSIX systems |
Which method to use
| Task | Use |
|---|---|
| Create a path | Path.of("a", "b", "c.txt") |
| Combine a directory and a name | dir.resolve(name) |
| Check that a user-supplied name stays inside a directory | dir.resolve(name).normalize().startsWith(dir)toRealPath() |
| Do two paths name the same file? | Files.isSameFile |
| Copy and keep timestamps | Files.copyCOPY_ATTRIBUTES |
| Replace a file that others read | Write a temporary file, then Files.moveATOMIC_MOVE |
| Delete a directory tree | Files.walkFileTree |
| Several attributes of many files | Files.readAttributes(path, BasicFileAttributes.class) |
| Are two files identical? | Files.mismatch(a, b) == -1 |
For reading and writing file content, see