Java Files: Copying, Moving, Deleting and Reading File Attributes
Copy, move and delete files with java.nio.file.Files: REPLACE_EXISTING, COPY_ATTRIBUTES and ATOMIC_MOVE, copying to and from streams, delete versus deleteIfExists, exists and isRegularFile checks, size, BasicFileAttributes and PosixFileAttributes, timestamps, symbolic links and isSameFile.
kvi5hnuCode Sprout team member9 min readOn this page
The previous article covered file contents. This one covers managing files as a whole: copying, moving and deleting them, and finding out what they are, how big they are, when they changed and who may access them.
Copying files
Files.copy(fromPath, toPath);
The copy fails with FileAlreadyExistsException if the target exists. Options change the behavior:
StandardCopyOption.REPLACE_EXISTINGoverwrites an existing target. A non-empty directory still can't be replaced.StandardCopyOption.COPY_ATTRIBUTEScopies attributes such as the last-modified time and, where supported, permissions. Without it, the copy gets a fresh timestamp.LinkOption.NOFOLLOW_LINKScopies a symbolic link itself instead of the file it points to.
Files.copy(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
Copying a directory creates an empty directory at the target. Its entries aren't copied. Copying a tree takes a walk over the directory, as article 28 shows.
Files.copy also connects files with streams:
Files.copy(inputStream, toPath); // save a stream to a file; returns the byte count
Files.copy(fromPath, outputStream); // send a file to a stream
The first form is handy for saving a download or an upload. It accepts REPLACE_EXISTING.
Moving and renaming
Files.move(fromPath, toPath);
Within the same directory, that's a rename. Like copy, it fails if the target exists unless you pass REPLACE_EXISTING. Moving within one file system is usually a quick rename of the directory entry. Moving across file systems, such as to another drive, means copying and then deleting, and a directory can only be moved that way if it's empty.
ATOMIC_MOVE demands that the move happen as a single atomic operation: either it completes entirely, or the source stays in place. Other processes never see a half-moved file. If the file system can't do it atomically, which is always the case across file systems, the call throws AtomicMoveNotSupportedException instead of falling back. This is the standard technique for safely replacing a file: write the new contents to a temporary file in the same directory, then atomically move it over the original.
Path temp = Files.createTempFile(config.getParent(), "config", ".tmp");
Files.writeString(temp, newContents);
Files.move(temp, config, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
Whether REPLACE_EXISTING is honored together with ATOMIC_MOVE is up to the file system, but on POSIX systems and on Windows the replacing atomic rename works.
Deleting
Files.delete(path); // throws NoSuchFileException if missing
boolean deleted = Files.deleteIfExists(path); // false if missing
Both delete files, symbolic links (not their targets) and empty directories. A non-empty directory causes a DirectoryNotEmptyException. To delete a whole tree, delete the contents bottom-up, as the demos in this part do with Files.walk sorted in reverse order.
On Windows, a file that's open in another program usually can't be deleted. On Unix it can: the name disappears, and the data is removed once the last program closes it.
Checking files
These Files methods return a boolean:
exists(path)andnotExists(path). Both can befalseif the existence can't be determined, for example because of missing permissions.isRegularFile,isDirectory,isSymbolicLinkisReadable,isWritable,isExecutableisHidden. On Unix, a file is hidden if its name starts with a dot. On Windows, the DOS hidden attribute decides.isSameFile(p, q), whether two paths refer to the same file, following links
By default these follow symbolic links: isRegularFile(link) describes the file the link points to. Pass LinkOption.NOFOLLOW_LINKS to ask about the link itself.
Files.size(path) returns the size in bytes. Files.getLastModifiedTime and setLastModifiedTime get and set the modification time as a FileTime, which converts to and from Instant. Files.getOwner returns the owner as a UserPrincipal.
File attributes
Every file system provides a set of basic attributes, which you can read in one efficient call:
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
BasicFileAttributes provides:
creationTime(),lastAccessTime()andlastModifiedTime()asFileTimeobjects. If a file system doesn't track one of them, it reports another time instead.isRegularFile(),isDirectory(),isSymbolicLink()andisOther()(anything else, such as a device)size()fileKey(), an object that may uniquely identify the file, such as the device and inode number on Unix, ornull
On POSIX-compliant systems (Linux, macOS), you can read PosixFileAttributes instead, which adds the owner, the group and the permissions:
PosixFileAttributes posix = Files.readAttributes(path, PosixFileAttributes.class);
String perms = PosixFilePermissions.toString(posix.permissions()); // like "rw-r-----"
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rw-------"));
Windows has DosFileAttributes (read-only, hidden, archive, system). FileSystems.getDefault().supportedFileAttributeViews() tells you which attribute views are available, such as "basic", "posix", "dos", "owner" or "acl". Because these details differ so much between systems, check before using them, as the demo does. Files.getAttribute(path, "posix:permissions") and setAttribute access single attributes by name.
Symbolic links
A symbolic link is a small file that points to another path. Files.createSymbolicLink(link, target) creates one, Files.readSymbolicLink(link) returns its target, and path.toRealPath() resolves all links and returns the real, absolute path of an existing file. Most Files operations follow links automatically. Pass LinkOption.NOFOLLOW_LINKS when you need to work with the link itself. On Windows, creating symbolic links may require special privileges or developer mode.
A complete example
The demo sets the source file's timestamp to a fixed value so the output is reproducible. The POSIX and symbolic link parts assume a Unix-like system, such as the one the code runner uses.
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.time.Instant;
import java.util.*;
import java.util.stream.*;
import static java.nio.file.StandardCopyOption.*;
public class Solution {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("copydemo");
Path source = dir.resolve("source.txt");
Files.writeString(source, "important data\n");
FileTime fixed = FileTime.from(Instant.parse("2025-09-16T10:00:00Z"));
Files.setLastModifiedTime(source, fixed);
// copy: fails if the target exists, unless REPLACE_EXISTING
Path target = dir.resolve("target.txt");
Files.copy(source, target);
try {
Files.copy(source, target);
} catch (FileAlreadyExistsException e) {
System.out.println("second copy: FileAlreadyExistsException");
}
Files.copy(source, target, REPLACE_EXISTING);
System.out.println("plain copy keeps the timestamp: " + Files.getLastModifiedTime(target).equals(fixed));
Files.copy(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES);
System.out.println("COPY_ATTRIBUTES keeps the timestamp: " + Files.getLastModifiedTime(target).equals(fixed));
// copying between streams and files
Path fromStream = dir.resolve("from-stream.txt");
long n = Files.copy(new ByteArrayInputStream("saved from a stream".getBytes()), fromStream);
System.out.println("copied " + n + " bytes from an input stream");
var sink = new ByteArrayOutputStream();
Files.copy(fromStream, sink);
System.out.println("copied to an output stream: " + sink);
// move = rename; ATOMIC_MOVE for all-or-nothing
Path moved = dir.resolve("renamed.txt");
Files.move(target, moved);
System.out.println("after move: target exists " + Files.exists(target) + ", renamed exists " + Files.exists(moved));
Path temp = dir.resolve("config.tmp");
Files.writeString(temp, "version=2\n");
Path config = dir.resolve("config.properties");
Files.writeString(config, "version=1\n");
Files.move(temp, config, ATOMIC_MOVE, REPLACE_EXISTING);
System.out.println("config now: " + Files.readString(config).strip());
// delete and deleteIfExists
Files.delete(moved);
try {
Files.delete(moved);
} catch (NoSuchFileException e) {
System.out.println("delete twice: NoSuchFileException");
}
System.out.println("deleteIfExists: " + Files.deleteIfExists(moved));
Path sub = Files.createDirectory(dir.resolve("sub"));
Files.writeString(sub.resolve("f.txt"), "x");
try {
Files.delete(sub);
} catch (DirectoryNotEmptyException e) {
System.out.println("deleting a non-empty directory: DirectoryNotEmptyException");
}
// simple checks
System.out.println("exists: " + Files.exists(source) + ", notExists(missing): " + Files.notExists(dir.resolve("missing")));
System.out.println("isRegularFile: " + Files.isRegularFile(source) + ", isDirectory(dir): " + Files.isDirectory(dir));
System.out.println("readable/writable: " + Files.isReadable(source) + "/" + Files.isWritable(source));
System.out.println("size: " + Files.size(source));
Path hidden = Files.writeString(dir.resolve(".hidden"), "");
System.out.println(".hidden is hidden on Unix: " + Files.isHidden(hidden));
// basic attributes in one call
BasicFileAttributes attrs = Files.readAttributes(source, BasicFileAttributes.class);
System.out.println("attributes: size=" + attrs.size() + ", regular=" + attrs.isRegularFile()
+ ", directory=" + attrs.isDirectory() + ", modified=" + attrs.lastModifiedTime().toInstant());
// POSIX permissions, where supported
if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
Files.setPosixFilePermissions(source, PosixFilePermissions.fromString("rw-r-----"));
PosixFileAttributes posix = Files.readAttributes(source, PosixFileAttributes.class);
System.out.println("POSIX permissions: " + PosixFilePermissions.toString(posix.permissions()));
}
// symbolic links and isSameFile
Path link = dir.resolve("link.txt");
Files.createSymbolicLink(link, source);
System.out.println("isSymbolicLink: " + Files.isSymbolicLink(link)
+ ", isRegularFile(link): " + Files.isRegularFile(link)
+ ", without following: " + Files.isRegularFile(link, LinkOption.NOFOLLOW_LINKS));
System.out.println("readSymbolicLink: " + dir.relativize(Files.readSymbolicLink(link)));
System.out.println("isSameFile(link, source): " + Files.isSameFile(link, source));
System.out.println("toRealPath ends with source.txt: " + link.toRealPath().endsWith("source.txt"));
try (Stream<Path> paths = Files.walk(dir)) {
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(p);
}
}
}
second copy: FileAlreadyExistsException
plain copy keeps the timestamp: false
COPY_ATTRIBUTES keeps the timestamp: true
copied 19 bytes from an input stream
copied to an output stream: saved from a stream
after move: target exists false, renamed exists true
config now: version=2
delete twice: NoSuchFileException
deleteIfExists: false
deleting a non-empty directory: DirectoryNotEmptyException
exists: true, notExists(missing): true
isRegularFile: true, isDirectory(dir): true
readable/writable: true/true
size: 15
.hidden is hidden on Unix: true
attributes: size=15, regular=true, directory=false, modified=2025-09-16T10:00:00Z
POSIX permissions: rw-r-----
isSymbolicLink: true, isRegularFile(link): true, without following: false
readSymbolicLink: source.txt
isSameFile(link, source): true
toRealPath ends with source.txt: true
Common questions
How do I copy or delete a whole directory?
Files.copy and Files.delete handle one entry at a time. Walk the tree as shown in the next article: copy parents before children, delete children before parents.
How do I make a file executable or private on Linux and macOS?
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rwx------")) sets all permission bits at once. path.toFile().setExecutable(true) is a quick way to add just the execute bit, and it also works on Windows, where it mostly has no effect.
Why is creationTime() the same as the modification time?
Not every file system records creation time, and on some Linux file systems Java cannot read it. In that case the attribute falls back to another timestamp, as the article explains. Don't rely on creation time for program logic.
Can I move a file to the recycle bin instead of deleting it?
java.awt.Desktop.getDesktop().moveToTrash(file) (Java 9) does that on desktop systems that support it. Check Desktop.isDesktopSupported() and isSupported(Desktop.Action.MOVE_TO_TRASH) first; servers usually have no trash.
How do I show a file size as "1.4 MB"?
There is no JDK method for binary units like that. Divide by 1024 repeatedly and format the result, or use CompactNumberFormat (article 72) for decimal units such as "1.4M" in the user's locale.
move with ATOMIC_MOVE fails across drives. What now?
An atomic move is impossible between file systems. Copy the file into the target directory under a temporary name, then atomically move it to its final name within that file system, and finally delete the source.
API reference
java.nio.file.Files
| Method | Description |
|---|---|
static Path copy(Path source, Path target, CopyOption... options) | copies a file (or creates an empty directory) |
static long copy(InputStream in, Path target, CopyOption... options), static long copy(Path source, OutputStream out) | copies between streams and files; returns the byte count |
static Path move(Path source, Path target, CopyOption... options) | moves or renames |
static void delete(Path path), static boolean deleteIfExists(Path path) | deletes a file, link or empty directory |
static boolean exists(Path path, LinkOption... options), notExists(...) | existence checks |
static boolean isRegularFile(Path path, LinkOption... options), isDirectory(...), isSymbolicLink(Path path) | type checks |
static boolean isReadable(Path path), isWritable(...), isExecutable(...), isHidden(...) | access and visibility checks |
static boolean isSameFile(Path path, Path path2) | whether both paths locate the same file |
static long size(Path path) | the size in bytes |
static FileTime getLastModifiedTime(Path path, LinkOption... options), static Path setLastModifiedTime(Path path, FileTime time) | the modification time |
static UserPrincipal getOwner(Path path, LinkOption... options) | the owner |
static <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) | reads attributes of a given type |
static Set<PosixFilePermission> getPosixFilePermissions(Path path, LinkOption... options), setPosixFilePermissions(Path path, Set<PosixFilePermission> perms) | POSIX permissions |
static Path createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs), static Path readSymbolicLink(Path link) | create and read symbolic links |
java.nio.file.StandardCopyOption and java.nio.file.LinkOption
| Constant | Meaning |
|---|---|
REPLACE_EXISTING | replace the target if it exists |
COPY_ATTRIBUTES | copy attributes along with the content |
ATOMIC_MOVE | move atomically, or fail |
NOFOLLOW_LINKS | work with a symbolic link itself |
java.nio.file.attribute.BasicFileAttributes
| Method | Description |
|---|---|
FileTime creationTime(), lastAccessTime(), lastModifiedTime() | timestamps |
boolean isRegularFile(), isDirectory(), isSymbolicLink(), isOther() | the file type |
long size() | the size in bytes |
Object fileKey() | a key that may uniquely identify the file, or null |
java.nio.file.attribute.FileTime
| Method | Description |
|---|---|
static FileTime from(Instant instant), Instant toInstant() | conversion to and from Instant |
java.nio.file.Path
| Method | Description |
|---|---|
Path toRealPath(LinkOption... options) | the real absolute path of an existing file, with links resolved |
Summary
Files.copyandFiles.movefail if the target exists, unless you passREPLACE_EXISTING.COPY_ATTRIBUTESpreserves timestamps and permissions.ATOMIC_MOVEmakes a move all-or-nothing. Write to a temp file in the same directory and move it over the original to replace files safely.deletethrows for a missing file anddeleteIfExistsreturnsfalse. Only empty directories can be deleted.exists,isRegularFile,isDirectory,isHidden,isSameFileand friends check files. They follow symbolic links unless you passNOFOLLOW_LINKS, and their answers can go stale.readAttributeswithBasicFileAttributesreads type, size and timestamps in one call.PosixFileAttributesand permissions are available on Unix-like systems.
Practice Questions
What happens when you call Files.copy(a, b) twice in a row?
The second call throws FileAlreadyExistsException, because b now exists. Pass StandardCopyOption.REPLACE_EXISTING to overwrite.
Why should the temporary file for an atomic replacement be in the same directory as the target, not in /tmp?
/tmp may be on a different file system, and an atomic move is only possible within one file system. Across file systems, ATOMIC_MOVE throws AtomicMoveNotSupportedException.
Files.delete(dir) throws DirectoryNotEmptyException. How do you delete the directory with everything in it?
Delete its contents bottom-up: try (var paths = Files.walk(dir)) { for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(p); }. Reverse order visits files before the directories that contain them.
link.txt is a symbolic link to data.txt. What do Files.isRegularFile(link) and Files.isRegularFile(link, LinkOption.NOFOLLOW_LINKS) return?
true and false. The first follows the link and examines data.txt. The second examines the link itself, which is a symbolic link, not a regular file.
How do you get a file's size and last modification time with a single file system access?
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);, then attrs.size() and attrs.lastModifiedTime(). Separate calls to Files.size and Files.getLastModifiedTime would each access the file system.
Previous: Java Files: Reading, Writing and Creating Files and Directories
Next: Java Directory Traversal: Files.list, walk, find, Glob Patterns and FileVisitor
Related reading
- Java Files: Reading, Writing and Creating Files and Directories
- Java NIO Path: Creating, Resolving, Relativizing and Normalizing Paths
- Java ZIP Archives: ZipInputStream, ZipOutputStream and ZIP File Systems
- Java RandomAccessFile: Seeking and Fixed-Size Records
- Java DataInput and DataOutput: Reading and Writing Binary Data

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.