Java Files API
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
Patharguments and never hold any state between calls. - Failures throw specific exceptions (
NoSuchFileException,FileAlreadyExistsException,AccessDeniedException,DirectoryNotEmptyException, ...), all subclasses ofIOException, each carrying the affected path. - Behaviour is controlled with option arguments:
StandardOpenOptionfor opening,StandardCopyOptionfor copying and moving,LinkOption.NOFOLLOW_LINKSfor 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
| Group | Methods |
|---|---|
| Check | exists, notExists, isRegularFile, isDirectory, isSymbolicLink, isReadable, isWritable, isExecutable, isHidden, isSameFile |
| Create | createFile, createDirectory, createDirectories, createTempFile, createTempDirectory, createLink, createSymbolicLink |
| Read whole content | readString, readAllLines, readAllBytes |
| Write whole content | writeString, write(path, bytes), write(path, lines) |
| Open for streaming | newBufferedReader, newBufferedWriter, newInputStream, newOutputStream, newByteChannel, lines |
| Copy, move, delete | copy (3 forms), move, delete, deleteIfExists |
| Directories | list, newDirectoryStream, walk, find, walkFileTree |
| Metadata | size, getLastModifiedTime, setLastModifiedTime, readAttributes, getAttribute, setAttribute, getPosixFilePermissions, setPosixFilePermissions, getOwner, getFileStore, probeContentType |
| Compare | mismatch, isSameFile |
| Links | readSymbolicLink |
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/>
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.- The target must not exist unless you pass
REPLACE_EXISTING; otherwiseFileAlreadyExistsException. This default protects against accidentally overwriting data. COPY_ATTRIBUTESalso 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.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.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()andfileKey(). When you need several attributes, this is faster than callingFiles.size,Files.getLastModifiedTimeandFiles.isDirectoryseparately, 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 aMap. The string form is flexible but not type-safe — the values areObjects.FileTimeis the type for file timestamps; convert withtoInstant()andFileTime.from(instant).
Attribute views depend on the operating system
| View | Available on | Provides |
|---|---|---|
basic | All | Size, times, file type |
posix | Linux, macOS | Owner, group, rwx permissions |
unix | Linux, macOS (JDK-specific) | Link count, inode, uid/gid |
dos | Windows (also readable on Linux for compatibility) | Read-only, hidden, archive, system flags |
acl | Windows | Access control lists |
owner | Most | File owner |
user | Many file systems | Custom 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,isExecutablecheck whether this process currently has that access, taking the user, group and permissions into account. As withexists, the answer can change immediately afterwards, so they're for informative checks, not a replacement for handlingAccessDeniedException.probeContentType(path)guesses a MIME type — used, for example, to set theContent-Typeheader when serving files. On most systems it's based on the file extension (it reportedapplication/pdffor a file that isn't really a PDF, andtext/csvfor a file that doesn't exist). It can returnnullwhen 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-1if they're identical.price=4999\nis 11 bytes andlevel=another 6, so the first difference (bvsa) 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 copyc.txthas identical content but is a different file.existsandnotExistsaren't opposites. Both returnfalsewhen 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.
Symbolic and Hard Links
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 is | A small file containing a path to another file | A second name for the same file data |
| Can point to directories / other file systems | Yes | No |
| If the target is deleted | The link remains but is dangling — it points to nothing | The data remains; it's deleted only when the last name is removed |
Detected by isSymbolicLink | Yes | No — 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
Filesmethods follow symbolic links. After the target is deleted,exists(sym)isfalsebecause it follows the link to a missing file; withNOFOLLOW_LINKS, it reports that the link itself still exists — a dangling link. - The
unix:nlinkattribute 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:nlinkisn'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:
needsCopychecks 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 byCOPY_ATTRIBUTESon the previous sync) mean the file is unchanged. Only when the times differ but the sizes match does it fall back tomismatch, which compares the content — that catches files that were rebuilt with identical output, so they aren't copied needlessly.- Relative paths connect the two trees. Each source file's path relative to
build(css/site.css) is resolved againstdeploy, and the relative paths are collected inwanted. createDirectories(dst.getParent())makes sure subfolders likecssexist in the target before copying into them.- Removal pass. Any file in
deploywhose relative path isn't inwantedwas removed from the build (old-promo.html), so it's deleted from the deployment too. - 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.