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.File, which mixes a file name with operations on the file. It has real weaknesses: delete() and renameTo() return false without saying why, it knows nothing about symbolic links, permissions or other metadata, and listFiles() loads a whole directory into an array. Java 7 added the NIO.2 API (JSR 203, package java.nio.file), which splits the job into separate parts:

  • Path is an interface for a location: a root such as / or C:\ and a sequence of names. Creating and combining paths is pure string work and never touches the disk.
  • Files is a class of static methods that do the work: create, read, write, copy, move, delete, list and read attributes. Each failure is a specific IOException subclass, such as NoSuchFileException or DirectoryNotEmptyException.
  • Every Path belongs to a FileSystem, and each file system has a FileSystemProvider that Files delegates to. The default one is the operating system's disk, but the JDK also ships a ZIP file system, so the same Files calls work inside a ZIP archive; see ZIP and GZIP.
The main parts of java.nio.file
TypeSinceRole
PathJava 7A location; methods such as resolve, relativize, normalize
Paths.getJava 7Creates a path; still works, but no longer recommended
Path.ofJava 11Creates a path; the preferred factory
FilesJava 7All operations on files and directories
FileSystems, FileSystemJava 7The default file system, ZIP file systems, path matchers
Attribute views (BasicFileAttributes, PosixFileAttributes, ...)Java 7Metadata such as size, times, owner and permissions
Files.readString, writeStringJava 11Whole text files in one call
Files.mismatchJava 12Compares two files byte by byte

All programs below were compiled and run on JDK 21 on Linux. Paths are printed with /; on Windows the separator and the root differ, but the methods behave the same way.

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 methods work on names only.

Java
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):

Output
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
Path methods used above
MethodResult
getFileName, getParent, getRootThe last name, everything before it, and /
getNameCount, subpath(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 shows
resolveSiblingReplaces the file name, keeping the directory
relativizeThe relative path from one location to another, in either direction
normalizeRemoves . and folds dir/.., purely by name

The two startsWith lines show a classic bug. Path.startsWith compares whole names, so /home/ana/... does not start with /home/an. The string version does, because it compares characters. That difference is exactly what you want for "is this file inside that directory" checks, as the next section shows.

Traps: equality, endsWith, traversal and links

Because a Path is a name, comparing two paths compares names, not files. The program shows where that surprises people, and then uses the same name rules to reject user-supplied file names that try to escape an upload directory.

Java
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:

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
  • data/../report.txt and report.txt are not equals, even though they usually name the same file. After normalize they are. Normalize before putting paths in a set or a map key.
  • endsWith("csv") is false for q1.csv, because Path.endsWith compares whole names. To check an extension, convert the file name to a string first.
  • relativize between an absolute and a relative path throws IllegalArgumentException. Call toAbsolutePath() on both first.
  • Path traversal: uploads.resolve("../../etc/passwd") points outside the upload directory, and resolve("/etc/passwd") replaces it completely. Normalizing and then checking with Path.startsWith rejected both and accepted the two legitimate names. Without normalize, the .. version would pass the check, because its first names are /srv/uploads.
  • A symbolic link and its target are different names, so equals is false, but Files.isSameFile asks the file system and returns true. toRealPath() resolves all links and gives the real location. It fails with NoSuchFileException for a missing file, so it doubles as an existence check. When links can point outside a directory, check the result of toRealPath() rather than normalize().

Creating, copying, moving and deleting

The Files methods report each problem with its own exception. The program works in a temporary directory, sets a fixed modification time on its test file so it can check which copies keep it, and triggers the common failures on purpose.

Java
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:

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
  • createDirectories created docs and docs/drafts in one call, and calling it again did nothing. createDirectory, for a single level, throws FileAlreadyExistsException instead.
  • A plain copy does not keep the modification time: the copy got the current time. COPY_ATTRIBUTES copies the timestamps and, where possible, the permissions. Backup and sync tools that compare times need it.
  • copy refuses to overwrite and throws FileAlreadyExistsException; REPLACE_EXISTING allows it. Files.copy(InputStream, Path) saves a stream straight to a file and returns the byte count, 8 here.
  • move renames within a directory or moves between directories. With ATOMIC_MOVE the rename is a single file system operation: other programs see either the old name or the new one. It throws AtomicMoveNotSupportedException when that is impossible, such as between two disks. Without it, a move between file systems is a copy followed by a delete.
  • Files.mismatch 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.
  • delete fails with DirectoryNotEmptyException on a directory that still has content; deleting a tree needs a walk, shown in Files.walk and DirectoryStream. deleteIfExists returns false instead of throwing when there is nothing to delete.

Checking Files.exists before an operation is usually pointless: another process can create or delete the file between the check and the operation. Do the operation and handle its exception. Also note that exists and notExists can both return false, when the file system cannot tell, for example because a directory on the path cannot be read.

File attributes and file stores

Metadata is grouped into views. The basic view exists everywhere; others, such as posix on Linux and macOS or acl and dos on Windows, depend on the file system. The program writes 12 bytes, sets a fixed modification time so the output is reproducible, reads attributes as typed objects and as a map, and changes the POSIX permissions.

Java
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):

Output
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. unix adds fields such as the inode number and dos is emulated with extended attributes; neither is available everywhere, so portable code sticks to basic and checks before using the others.
  • createTempFile creates files readable only by the owner (rw-------) on POSIX systems, a safe default for temporary data. rw-r----- adds read access for the group.
  • The string form "posix:size,isRegularFile,lastModifiedTime" returns a map of just those attributes, which is handy for generic tools. The typed form, readAttributes(file, PosixFileAttributes.class), is checked by the compiler and is the better choice in normal code.
  • Files.getFileStore describes the volume the file is on: free and usable space, and which attribute views it supports.

Reading attributes one at a time versus together

Each of Files.isRegularFile, Files.size and Files.getLastModifiedTime asks the operating system separately. readAttributes gets all basic attributes in one call. The difference matters when scanning many files, so the program creates 20,000 small files and asks the same three questions about each, three ways.

Java
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):

Output
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 stat calls per file, 60,000 in all, and were about twice as slow as one readAttributes per file. The java.io.File methods also make one call each. When you walk a directory tree, Files.walkFileTree hands each file's attributes to the visitor for free, so no extra call is needed at all.

Moving from java.io.File

File is not deprecated, and many older APIs still take one. Convert with file.toPath() and path.toFile() at the boundary and use Path and Files for the work.

java.io.File and its java.nio.file replacements
java.io.FileNIO.2What 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) or Files.newDirectoryStream(dir)Lazy; does not load a huge directory at once
file.length(), lastModified()Files.readAttributesAll attributes in one call
file.exists()Files.exists(path)Can tell "missing" apart from "unknown" with notExists
File.createTempFileFiles.createTempFileOwner-only permissions on POSIX systems

Which method to use

Choosing a Path or Files method
TaskUse
Create a pathPath.of("a", "b", "c.txt")
Combine a directory and a namedir.resolve(name)
Check that a user-supplied name stays inside a directorydir.resolve(name).normalize().startsWith(dir), or toRealPath() when links are possible
Do two paths name the same file?Files.isSameFile
Copy and keep timestampsFiles.copy with COPY_ATTRIBUTES
Replace a file that others readWrite a temporary file, then Files.move with ATOMIC_MOVE
Delete a directory treeFiles.walkFileTree; see Files.walk
Several attributes of many filesFiles.readAttributes(path, BasicFileAttributes.class)
Are two files identical?Files.mismatch(a, b) == -1

For reading and writing file content, see reading a text file, writing a text file and file open options.