Java Files API

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 148 of 306

The Files Class

java.nio.file.Files is a utility class made entirely of static methods that operate on Path objects. It's the main entry point for file work in modern Java: almost every operation from the previous lessons — creating, reading, writing, deleting, listing and walking — is a Files method.

The methods share a common design, which is what makes the API reliable:

  • They take Path arguments and never hold any state between calls.
  • Failures throw specific exceptions (NoSuchFileException, FileAlreadyExistsException, AccessDeniedException, DirectoryNotEmptyException, ...), all subclasses of IOException, each carrying the affected path.
  • Behaviour is controlled with option arguments: StandardOpenOption for opening, StandardCopyOption for copying and moving, LinkOption.NOFOLLOW_LINKS for symbolic links.
  • Text methods default to UTF-8.
  • Methods that return streams or channels leave the file open until you close them; methods that return data (readString, readAllBytes, size) open and close files internally.

This lesson gives an overview of the whole class, then covers the groups not yet explained in detail: copying, attributes, comparison and links.

Overview of the Main Methods

GroupMethods
Checkexists, notExists, isRegularFile, isDirectory, isSymbolicLink, isReadable, isWritable, isExecutable, isHidden, isSameFile
CreatecreateFile, createDirectory, createDirectories, createTempFile, createTempDirectory, createLink, createSymbolicLink
Read whole contentreadString, readAllLines, readAllBytes
Write whole contentwriteString, write(path, bytes), write(path, lines)
Open for streamingnewBufferedReader, newBufferedWriter, newInputStream, newOutputStream, newByteChannel, lines
Copy, move, deletecopy (3 forms), move, delete, deleteIfExists
Directorieslist, newDirectoryStream, walk, find, walkFileTree
Metadatasize, getLastModifiedTime, setLastModifiedTime, readAttributes, getAttribute, setAttribute, getPosixFilePermissions, setPosixFilePermissions, getOwner, getFileStore, probeContentType
Comparemismatch, isSameFile
LinksreadSymbolicLink

Copying Files

Files.copy has three forms: file to file, stream to file, and file to stream.

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import static java.nio.file.StandardCopyOption.*;

public class Cp {
    public static void main(String[] args) throws IOException {
        Path src = Files.writeString(Path.of("logo.svg"), "<svg/>");
        Files.setLastModifiedTime(src, FileTime.from(Instant.parse("2026-01-01T00:00:00Z")));

        Path plain = Files.copy(src, Path.of("logo-copy.svg"));
        System.out.println("copy:            " + plain + ", same timestamp as source: "
            + Files.getLastModifiedTime(plain).equals(Files.getLastModifiedTime(src)));

        try {
            Files.copy(src, plain);
        } catch (FileAlreadyExistsException e) {
            System.out.println("copy again:      FileAlreadyExistsException " + e.getFile());
        }

        Files.copy(src, plain, REPLACE_EXISTING, COPY_ATTRIBUTES);
        System.out.println("COPY_ATTRIBUTES: modified " + Files.getLastModifiedTime(plain));

        try (InputStream upload = new ByteArrayInputStream("uploaded bytes".getBytes())) {
            long n = Files.copy(upload, Path.of("upload.bin"), REPLACE_EXISTING);
            System.out.println("stream -> file:  " + n + " bytes");
        }
        try (OutputStream out = new ByteArrayOutputStream()) {
            long n = Files.copy(src, out);
            System.out.println("file -> stream:  " + n + " bytes: " + out);
        }
    }
}

Output (on a fresh run):

copy:            logo-copy.svg, same timestamp as source: false
copy again:      FileAlreadyExistsException logo-copy.svg
COPY_ATTRIBUTES: modified 2026-01-01T00:00:00Z
stream -> file:  14 bytes
file -> stream:  6 bytes: <svg/>
  1. copy(source, target) copies the content into a new file and returns the target path. The copy gets a new modification time — the moment of copying.
  2. The target must not exist unless you pass REPLACE_EXISTING; otherwise FileAlreadyExistsException. This default protects against accidentally overwriting data.
  3. COPY_ATTRIBUTES also copies the modification time (and, where the file system supports it, permissions and other attributes). Backups and synchronisation tools rely on this, because they compare timestamps.
  4. copy(InputStream, target, options) writes everything from a stream into a file and returns the byte count. It's the one-line way to save an HTTP download or an uploaded file. The stream isn't closed by the method, so the caller closes it.
  5. copy(source, OutputStream) sends a file's bytes to a stream — for example, to an HTTP response when serving a download.

Copying a directory creates only an empty directory at the target; to copy a whole tree, walk it (Directory Handling lesson). Symbolic links are followed by default — the file they point to is copied — unless you pass LinkOption.NOFOLLOW_LINKS, which copies the link itself.

File Attributes

Besides content, every file has metadata. Files reads it through attribute views, groups of attributes defined by the operating system.

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.time.Instant;

public class Attr {
    public static void main(String[] args) throws IOException {
        Path f = Files.writeString(Path.of("invoice-1001.pdf"), "%PDF-1.7 fake");
        Files.setLastModifiedTime(f, FileTime.from(Instant.parse("2026-11-01T10:15:30Z")));

        BasicFileAttributes basic = Files.readAttributes(f, BasicFileAttributes.class);
        System.out.println("size=" + basic.size() + " regular=" + basic.isRegularFile()
            + " dir=" + basic.isDirectory() + " link=" + basic.isSymbolicLink()
            + " modified=" + basic.lastModifiedTime());

        System.out.println("getAttribute size: " + Files.getAttribute(f, "basic:size"));
        System.out.println("readAttributes map: " + Files.readAttributes(f, "basic:size,lastModifiedTime"));

        System.out.println("views supported: " + FileSystems.getDefault().supportedFileAttributeViews().stream().sorted().toList());
        PosixFileAttributes posix = Files.readAttributes(f, PosixFileAttributes.class);
        System.out.println("permissions: " + PosixFilePermissions.toString(posix.permissions()));
        Files.setPosixFilePermissions(f, PosixFilePermissions.fromString("rw-r-----"));
        System.out.println("after chmod:  " + PosixFilePermissions.toString(Files.getPosixFilePermissions(f)));

        System.out.println("readable=" + Files.isReadable(f) + " writable=" + Files.isWritable(f) + " executable=" + Files.isExecutable(f));
        System.out.println("content type: " + Files.probeContentType(f) + ", for .csv: " + Files.probeContentType(Path.of("x.csv")));
    }
}

Output (on Linux; initial permissions depend on the system's umask):

size=13 regular=true dir=false link=false modified=2026-11-01T10:15:30Z
getAttribute size: 13
readAttributes map: {lastModifiedTime=2026-11-01T10:15:30Z, size=13}
views supported: [basic, dos, owner, posix, unix, user]
permissions: rw-r--r--
after chmod:  rw-r-----
readable=true writable=true executable=false
content type: application/pdf, for .csv: text/csv

Reading attributes

  • readAttributes(path, BasicFileAttributes.class) reads a whole group of attributes in one file-system call and returns them as an object: size(), lastModifiedTime(), lastAccessTime(), creationTime(), isRegularFile(), isDirectory(), isSymbolicLink() and fileKey(). When you need several attributes, this is faster than calling Files.size, Files.getLastModifiedTime and Files.isDirectory separately, each of which queries the file system again.
  • getAttribute(path, "view:name") reads one attribute by name; readAttributes(path, "view:a,b") reads several into a Map. The string form is flexible but not type-safe — the values are Objects.
  • FileTime is the type for file timestamps; convert with toInstant() and FileTime.from(instant).

Attribute views depend on the operating system

ViewAvailable onProvides
basicAllSize, times, file type
posixLinux, macOSOwner, group, rwx permissions
unixLinux, macOS (JDK-specific)Link count, inode, uid/gid
dosWindows (also readable on Linux for compatibility)Read-only, hidden, archive, system flags
aclWindowsAccess control lists
ownerMostFile owner
userMany file systemsCustom key-value metadata

Code that uses PosixFileAttributes or setPosixFilePermissions throws UnsupportedOperationException on Windows. Check supportedFileAttributeViews().contains("posix") before using POSIX features in cross-platform code.

Permission checks and content type

  • isReadable, isWritable, isExecutable check whether this process currently has that access, taking the user, group and permissions into account. As with exists, the answer can change immediately afterwards, so they're for informative checks, not a replacement for handling AccessDeniedException.
  • probeContentType(path) guesses a MIME type — used, for example, to set the Content-Type header when serving files. On most systems it's based on the file extension (it reported application/pdf for a file that isn't really a PDF, and text/csv for a file that doesn't exist). It can return null when the type is unknown. Never use it as a security check on uploads; inspect the content instead (FileInputStream lesson).

Comparing Files

import java.io.IOException;
import java.nio.file.*;

public class Cmp {
    public static void main(String[] args) throws IOException {
        Path a = Files.writeString(Path.of("a.txt"), "price=4999\nlevel=beginner\n");
        Path b = Files.writeString(Path.of("b.txt"), "price=4999\nlevel=advanced\n");
        Path c = Files.copy(a, Path.of("c.txt"), StandardCopyOption.REPLACE_EXISTING);

        System.out.println("mismatch a,b: " + Files.mismatch(a, b));
        System.out.println("mismatch a,c: " + Files.mismatch(a, c));
        System.out.println("isSameFile a,c: " + Files.isSameFile(a, c));
        System.out.println("isSameFile a,./a.txt: " + Files.isSameFile(a, Path.of("./a.txt")));

        Path missing = Path.of("ghost.txt");
        System.out.println("exists=" + Files.exists(missing) + " notExists=" + Files.notExists(missing));
    }
}

Output:

mismatch a,b: 17
mismatch a,c: -1
isSameFile a,c: false
isSameFile a,./a.txt: true
exists=false notExists=true
  • mismatch(a, b) (Java 12+) compares two files' content byte by byte and returns the position of the first difference, or -1 if they're identical. price=4999\n is 11 bytes and level= another 6, so the first difference (b vs a) is at position 17. It reads both files in blocks and stops at the first difference, which is efficient even for large files. If the files have different lengths but one is a prefix of the other, it returns the shorter length.
  • isSameFile(a, b) asks whether two paths lead to the same file on disk — through ./.., symbolic links or hard links. It isn't a content comparison: the copy c.txt has identical content but is a different file.
  • exists and notExists aren't opposites. Both return false when Java can't determine whether the file exists (for example, when a parent directory isn't readable). !Files.exists(p) therefore doesn't prove the file is absent.
import java.io.IOException;
import java.nio.file.*;

public class Links {
    public static void main(String[] args) throws IOException {
        Path target = Files.writeString(Path.of("config-v2.yaml"), "port: 9090\n");
        Path sym = Path.of("config.yaml");
        Path hard = Path.of("config-hardlink.yaml");
        Files.deleteIfExists(sym);
        Files.deleteIfExists(hard);

        Files.createSymbolicLink(sym, target.getFileName());
        Files.createLink(hard, target);

        System.out.println("isSymbolicLink(sym)=" + Files.isSymbolicLink(sym) + ", points to " + Files.readSymbolicLink(sym));
        System.out.println("read via symlink: " + Files.readString(sym).strip());
        System.out.println("isSymbolicLink(hard)=" + Files.isSymbolicLink(hard) + ", same file: " + Files.isSameFile(hard, target));
        System.out.println("link count: " + Files.getAttribute(target, "unix:nlink"));

        Files.delete(target);
        System.out.println("after deleting target: symlink exists=" + Files.exists(sym)
            + " (dangling=" + Files.exists(sym, LinkOption.NOFOLLOW_LINKS) + "), hard link content: "
            + Files.readString(hard).strip());
    }
}

Output (on Linux or macOS):

isSymbolicLink(sym)=true, points to config-v2.yaml
read via symlink: port: 9090
isSymbolicLink(hard)=false, same file: true
link count: 2
after deleting target: symlink exists=false (dangling=true), hard link content: port: 9090
Symbolic link (createSymbolicLink)Hard link (createLink)
What it isA small file containing a path to another fileA second name for the same file data
Can point to directories / other file systemsYesNo
If the target is deletedThe link remains but is dangling — it points to nothingThe data remains; it's deleted only when the last name is removed
Detected by isSymbolicLinkYesNo — it's indistinguishable from the original name
  • readSymbolicLink(sym) returns the stored target path (config-v2.yaml), which may be relative, as here: it's resolved relative to the link's directory.
  • Most Files methods follow symbolic links. After the target is deleted, exists(sym) is false because it follows the link to a missing file; with NOFOLLOW_LINKS, it reports that the link itself still exists — a dangling link.
  • The unix:nlink attribute counts the names pointing to the file's data: 2 after creating the hard link. That's why the hard link can still be read after the original name is deleted.
  • On Windows, creating symbolic links requires administrator rights or Developer Mode, and unix:nlink isn't available.

Practical Example: Synchronising a Deployment Folder

Static-site generators and deployment scripts copy a build output folder to a server folder. Copying everything every time is slow and changes the timestamps of untouched files (which breaks browser and CDN caching). A sync copies only new or changed files and removes files that no longer exist in the build. This example combines many Files methods: walk, relativize/resolve, size, getLastModifiedTime, mismatch, copy with options and delete.

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.*;
import java.util.stream.Stream;
import static java.nio.file.StandardCopyOption.*;

public class Sync {
    record Report(List<String> copied, List<String> unchanged, List<String> removed) { }

    static boolean needsCopy(Path src, Path dst) throws IOException {
        if (Files.notExists(dst)) return true;
        if (Files.size(src) != Files.size(dst)) return true;
        if (Files.getLastModifiedTime(src).equals(Files.getLastModifiedTime(dst))) return false;
        return Files.mismatch(src, dst) != -1;
    }

    static Report sync(Path source, Path target) throws IOException {
        List<String> copied = new ArrayList<>(), unchanged = new ArrayList<>(), removed = new ArrayList<>();
        Set<Path> wanted = new HashSet<>();
        try (Stream<Path> files = Files.walk(source)) {
            for (Path src : files.filter(Files::isRegularFile).sorted().toList()) {
                Path rel = source.relativize(src);
                Path dst = target.resolve(rel);
                wanted.add(rel);
                if (needsCopy(src, dst)) {
                    Files.createDirectories(dst.getParent());
                    Files.copy(src, dst, REPLACE_EXISTING, COPY_ATTRIBUTES);
                    copied.add(rel.toString());
                } else {
                    unchanged.add(rel.toString());
                }
            }
        }
        if (Files.exists(target)) {
            try (Stream<Path> files = Files.walk(target)) {
                for (Path dst : files.filter(Files::isRegularFile).sorted().toList()) {
                    Path rel = target.relativize(dst);
                    if (!wanted.contains(rel)) {
                        Files.delete(dst);
                        removed.add(rel.toString());
                    }
                }
            }
        }
        return new Report(copied, unchanged, removed);
    }

    public static void main(String[] args) throws IOException {
        Path build = Path.of("build");
        Path deploy = Path.of("deploy");
        Files.createDirectories(build.resolve("css"));
        Files.writeString(build.resolve("index.html"), "<h1>Home</h1>");
        Files.writeString(build.resolve("css/site.css"), "body{}");
        System.out.println("first:  " + sync(build, deploy));

        Files.writeString(build.resolve("index.html"), "<h1>Welcome</h1>");
        Files.writeString(build.resolve("about.html"), "<h1>About</h1>");
        Files.writeString(deploy.resolve("old-promo.html"), "expired");
        System.out.println("second: " + sync(build, deploy));
        System.out.println("third:  " + sync(build, deploy));
    }
}

Output (on a fresh run):

first:  Report[copied=[css/site.css, index.html], unchanged=[], removed=[]]
second: Report[copied=[about.html, index.html], unchanged=[css/site.css], removed=[old-promo.html]]
third:  Report[copied=[], unchanged=[about.html, css/site.css, index.html], removed=[]]

How it works:

  1. needsCopy checks from cheapest to most expensive. A missing target or a different size proves the file must be copied without reading any content. Equal sizes and equal modification times (preserved by COPY_ATTRIBUTES on the previous sync) mean the file is unchanged. Only when the times differ but the sizes match does it fall back to mismatch, which compares the content — that catches files that were rebuilt with identical output, so they aren't copied needlessly.
  2. Relative paths connect the two trees. Each source file's path relative to build (css/site.css) is resolved against deploy, and the relative paths are collected in wanted.
  3. createDirectories(dst.getParent()) makes sure subfolders like css exist in the target before copying into them.
  4. Removal pass. Any file in deploy whose relative path isn't in wanted was removed from the build (old-promo.html), so it's deleted from the deployment too.
  5. The three runs show the behaviour: the first copies everything; the second copies only the new and changed pages, keeps the untouched stylesheet and removes the stale page; the third finds nothing to do.

Tools like rsync follow the same strategy. A production version would also delete directories left empty after the removal pass, and might copy into a temporary folder and switch over atomically, so visitors never see a half-updated site.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Files API and get answers drawn from it.

Signed-in readers only.