Skip to content

Java: Create, Copy, Move, and Delete Files and Directories

Two light card-stock trays against oxblood red, a white index card in the left one, an identical card in the right one whose upper half is still forming from particles of light; a beam of light connects the two

With the Files class, you create files and directories, check whether they exist, and copy, move, rename, and delete them. Each of these operations is a single method call, and every error arrives as an exception that names the path and the cause.

A log rotation, for example, looks like this:

Path logDir = Path.of("target/logs");
Path log = logDir.resolve("server.log");

Files.createDirectories(logDir);
if (Files.exists(log)) {
  Files.move(log, logDir.resolve("server.log.1"), REPLACE_EXISTING);
}
Files.createFile(log);

Afterwards, target/logs/ contains the previous log file (if it existed) under the new name and a new, empty file under the old one:

server.log (0 bytes)
server.log.1 (276 bytes)

Files.createDirectories() creates the directory, including any missing parent directories, and does nothing if the directory already exists. Files.move() renames the existing log file; REPLACE_EXISTING replaces the file server.log.1 from the previous rotation. Finally, Files.createFile() creates the new, empty log file.

The Files class belongs to the NIO.2 API, which was introduced in Java 7 with JSR 203. All methods in this article have existed since Java 7 – except Files.writeString() from Java 11 and Files.mismatch() from Java 12.

In this article, you will find out

  • why I recommend Files over File and which Files method replaces which File method,
  • how to check whether a file exists – and why exists() and notExists() can both return false,
  • why “check first, then create” can lead to a race condition and how createFile() avoids it,
  • how createDirectory() and createDirectories() differ,
  • how to create temporary files and delete them again,
  • what copy() does with attributes, symbolic links, and a directory as the target,
  • how to move and rename files and replace them atomically with ATOMIC_MOVE,
  • how to copy and delete a directory with all its contents,
  • how to create symbolic links and hard links,
  • how fast Files.copy() is compared to transferTo() and a copy loop.

The Examples in This Article

Every example starts with a fresh directory target/logs/ that contains a copy of the file files/server.log – the log file with five lines from the article about the BufferedReader, 276 bytes in size. The method Examples.reset() from the example repository creates this directory, and Examples.printTree() prints what it contains after an operation: directories with a slash, files with their size.

You can find the complete code in the GitHub repository java-file-io, in the package eu.happycoders.files. Each section has its own class there with a main() method that produces the outputs shown. Start the classes in the root directory of the repository; everything the examples create ends up in the target/ directory.

The examples use language features from Java 25 and therefore run only from that version on. The individual Files calls work from Java 7 on; before Java 11, replace Path.of() with Paths.get(). The outputs come from macOS; where Linux or Windows differ, the text says so.

Files vs. File: Which API Should You Use?

For every operation in this article, there are two APIs: the class java.io.File from Java 1.0 and the class java.nio.file.Files from Java 7.

I recommend Files – because of the error messages: The methods of File return true or false. If an operation fails, you don’t find out why. The methods of Files, on the other hand, throw an exception that names the path and the cause.

The following example tries to move the log file into a directory that doesn’t exist – once with File.renameTo() and once with Files.move():

File log = new File("target/logs/server.log");
File target = new File("target/old/server.log");
System.out.println("renameTo(): " + log.renameTo(target));
try {
  Files.move(log.toPath(), target.toPath());
} catch (IOException e) {
  System.out.println(e);
}
renameTo(): false
java.nio.file.NoSuchFileException: target/logs/server.log -> target/old/server.log

renameTo() returns false, and the file is still in its place. Nothing tells you why the operation failed – a missing target directory, missing permissions, or a target on another drive, for example. Files.move(), on the other hand, throws a NoSuchFileException with both paths. The Javadoc of renameTo() itself calls the method’s behavior “inherently platform-dependent” and refers to Files.move().

The following table shows which Files method replaces which File method. The File column shows ✗ where the class has no method for the operation:

Operationjava.io.Filejava.nio.file.Files
Check existenceexists(), isFile(), isDirectory()exists(), notExists(), isRegularFile(), isDirectory()
Create a filecreateNewFile()createFile()
Create a directorymkdir(), mkdirs()createDirectory(), createDirectories()
Create a temporary filecreateTempFile()createTempFile(), createTempDirectory()
Copy✗copy()
Move, renamerenameTo()move()
Deletedelete(), deleteOnExit()delete(), deleteIfExists()
Create links✗createSymbolicLink(), createLink()

All Files methods take a Path object. If an older API gives you a File object, you convert it into a Path object with file.toPath(). The article about file and directory names with File, Path, and Paths shows how to construct Path objects.

Checking Whether a File Exists: Files.exists(), notExists(), isRegularFile(), and isDirectory()

Files.exists() returns true if something exists at the given path – a file, a directory, a link, or a device file. Files.isRegularFile() and Files.isDirectory() tell you whether it is a file or a directory. The following example queries the log file, its directory, and a file that doesn’t exist:

Path logDir = Path.of("target/logs");
Path log = logDir.resolve("server.log");
Path missing = logDir.resolve("missing.log");

System.out.println("exists(log):          " + Files.exists(log));
System.out.println("isRegularFile(log):   " + Files.isRegularFile(log));
System.out.println("isDirectory(log):     " + Files.isDirectory(log));
System.out.println("isDirectory(logDir):  " + Files.isDirectory(logDir));
System.out.println("exists(missing):      " + Files.exists(missing));
System.out.println("notExists(missing):   " + Files.notExists(missing));
exists(log):          true
isRegularFile(log):   true
isDirectory(log):     false
isDirectory(logDir):  true
exists(missing):      false
notExists(missing):   true

If isRegularFile() and isDirectory() both return false although exists() returns true, the entry is a file of type “other” – e.g., a named pipe, a device file, or a socket. All three methods follow a symbolic link to its target; Files.isSymbolicLink() tells you whether the path itself is a symbolic link.

None of the four methods throws an IOException. If the method cannot answer the question, it returns false – notExists() as well. The next two sections show what that means.

exists(), isRegularFile(), and isDirectory() follow symbolic links: They answer the question for the file the link points to. The following example creates the link current.log to the log file and then deletes the log file:

Path link = logDir.resolve("current.log");
Files.createSymbolicLink(link, Path.of("server.log"));
System.out.println("exists(link):                 " + Files.exists(link));
Files.delete(log);
System.out.println("exists(link) after delete:    " + Files.exists(link));
System.out.println("exists(link, NOFOLLOW_LINKS): "
    + Files.exists(link, NOFOLLOW_LINKS));
System.out.println("isSymbolicLink(link):         " + Files.isSymbolicLink(link));
exists(link):                 true
exists(link) after delete:    false
exists(link, NOFOLLOW_LINKS): true
isSymbolicLink(link):         true

After the log file has been deleted, exists(link) returns false, although the link is still in the directory. With the option LinkOption.NOFOLLOW_LINKS, you ask about the link itself, and the answer is true. isRegularFile(), isDirectory(), and notExists() take the same option.

When Existence Cannot Be Determined

notExists() is not the opposite of exists(). If the method cannot determine whether the file exists, both return false. The following example creates the file secret.log in a directory, then takes all permissions away from the directory and gives them back in the finally block – without permissions, the directory could no longer be deleted, not even on the next run of the example:

Path locked = logDir.resolve("locked");
Path secret = locked.resolve("secret.log");
Files.createDirectory(locked);
Files.createFile(secret);
Files.setPosixFilePermissions(locked, PosixFilePermissions.fromString("---------"));
try {
  System.out.println("exists(secret):    " + Files.exists(secret));
  System.out.println("notExists(secret): " + Files.notExists(secret));
} finally {
  Files.setPosixFilePermissions(locked, PosixFilePermissions.fromString("rwx------"));
}
exists(secret):    false
notExists(secret): false

The file exists, but without the permission to search the directory, the operating system answers the question about it with “permission denied” – neither yes nor no. On Linux and macOS, exists() calls the system function access() for this and returns false as soon as it reports an error. notExists() asks the same question but returns true only on a NoSuchFileException – on any other IOException, here an AccessDeniedException, it returns false as well.

So an if (!Files.exists(file)) doesn’t mean “the file is missing”, but “I couldn’t see it”. If you want to act because a file is missing – create a default configuration, for example – ask with notExists(). That is what the method is for.

Check First, Then Create? The Race Condition

The Javadoc of exists() says: The result is outdated the moment the method returns. Between your check and your next operation, another thread or another program can create, delete, or replace the file. Such an error, where the result depends on who gets to go first, is called a race condition. This variant has its own name: time-of-check to time-of-use, TOCTOU for short.

The following program shows how often that happens. Two threads run through the same loop: For each of 10,000 files, they check with notExists() whether the file is missing and then create it with createFile(). If createFile() fails despite the check, the thread counts a collision:

AtomicInteger collisions = new AtomicInteger();
CountDownLatch start = new CountDownLatch(1);
Runnable checkThenCreate =
    () -> {
      try {
        start.await();
        for (int i = 0; i < FILES; i++) {
          Path file = dir.resolve("file-" + i + ".log");
          if (Files.notExists(file)) {
            try {
              Files.createFile(file);
            } catch (FileAlreadyExistsException e) {
              collisions.incrementAndGet();
            }
          }
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      } catch (IOException e) {
        throw new UncheckedIOException(e);
      }
    };

Thread first = Thread.ofPlatform().start(checkThenCreate);
Thread second = Thread.ofPlatform().start(checkThenCreate);
start.countDown();
first.join();
second.join();

System.out.println(FILES + " files, " + collisions
    + " times notExists() was true and createFile() failed");
10000 files, 8114 times notExists() was true and createFile() failed

FILES is a constant with the value 10,000, dir the directory target/logs/race/. In my run, the check was already outdated 8,114 times before createFile() was called: Both threads saw “missing”, both called createFile(), and only one of them created the file. The two threads run in lockstep here, hence the high number – in a program in which two processes only occasionally create the same file, it happens less often, and that is why such an error goes unnoticed for a long time.

The following diagram shows such a collision using the file file-0.log as an example:

Timeline of two threads for the file file-0.log: Both call notExists() and get true while the file is missing. Then the first thread creates the file with createFile(), and the second thread’s createFile() throws a FileAlreadyExistsException.
Between the check and createFile(), the first thread creates the file – the second thread’s check is outdated

The explicit check isn’t even necessary, because createFile() checks by itself – and it does so atomically: Checking and creating are a single file-system operation, and of two simultaneous calls, exactly one succeeds. The same applies to createDirectory() and delete().

That is why I recommend exists() and notExists() only for decisions in which the race condition cannot do any damage: skipping an optional configuration file, printing a message, the log rotation from the introduction. Before creating, moving, or deleting, on the other hand, don’t check first: Call the operation and catch the exception, as the following sections show.

Creating Files with Files.createFile()

Files.createFile() creates a new, empty file and returns its path:

Path app = logDir.resolve("app.log");
Files.createFile(app);
System.out.println(app + ": " + Files.size(app) + " bytes");
target/logs/app.log: 0 bytes

If the file already exists, the method throws a FileAlreadyExistsException. If the directory the file is supposed to be in is missing, it throws a NoSuchFileException – createFile() doesn’t create directories:

try {
  Files.createFile(app);
} catch (FileAlreadyExistsException e) {
  System.out.println(e);
}
try {
  Files.createFile(Path.of("target/logs/2026/app.log"));
} catch (NoSuchFileException e) {
  System.out.println(e);
}
java.nio.file.FileAlreadyExistsException: target/logs/app.log
java.nio.file.NoSuchFileException: target/logs/2026/app.log

You also get a FileAlreadyExistsException if there is no regular file at the path but a directory or a symbolic link.

Creating a File If It Does Not Exist Yet

To create a file only if it is missing and leave it unchanged otherwise, call createFile() and catch the FileAlreadyExistsException. The following example does that twice in a row:

for (int run = 1; run <= 2; run++) {
  Path audit = logDir.resolve("audit.log");
  try {
    Files.createFile(audit);
    System.out.println("Run " + run + ": created " + audit);
  } catch (FileAlreadyExistsException e) {
    System.out.println("Run " + run + ": " + audit + " already exists");
  }
}
Run 1: created target/logs/audit.log
Run 2: target/logs/audit.log already exists

The first run creates the file, the second one gets the exception. A prior check with notExists() would only add the risk of a race condition, as shown in the section Check First, Then Create? The Race Condition.

The counterpart from the old API, File.createNewFile(), works just as atomically but returns only true or false:

File legacy = new File("target/logs/app.log");
System.out.println("createNewFile(): " + legacy.createNewFile());
createNewFile(): false

Creating a File with Content

If the new file should have content right away, you don’t need createFile(): Files.writeString() – available since Java 11 – creates the file if it is missing and overwrites it if it exists. With the option StandardOpenOption.CREATE_NEW, it only creates the file and otherwise throws a FileAlreadyExistsException:

Path notes = logDir.resolve("notes.txt");
Files.writeString(notes, "Rotated at 08:16\n");
System.out.println(notes + ": " + Files.size(notes) + " bytes");
try {
  Files.writeString(notes, "Rotated at 08:16\n", CREATE_NEW);
} catch (FileAlreadyExistsException e) {
  System.out.println(e);
}
target/logs/notes.txt: 17 bytes
java.nio.file.FileAlreadyExistsException: target/logs/notes.txt

Files.write(), Files.newBufferedWriter(), and Files.newOutputStream() take the same options as Files.writeString(). The article about writing files shows which options there are and how to append to a file.

Setting Permissions When Creating a File

On Linux and macOS, a new file gets the permissions that result from 0666 and the process’s umask – with the usual process umask 022, that is rw-r--r--: Every account on the system may read it. If that is not what you want, you pass the permissions to createFile() as a FileAttribute:

FileAttribute<Set<PosixFilePermission>> ownerOnly =
    PosixFilePermissions.asFileAttribute(
        PosixFilePermissions.fromString("rw-------"));
Path secret = Files.createFile(logDir.resolve("secret.log"), ownerOnly);
System.out.println(
    PosixFilePermissions.toString(Files.getPosixFilePermissions(secret)));
System.out.println(
    PosixFilePermissions.toString(Files.getPosixFilePermissions(app)));
rw-------
rw-r--r--

The first line shows the permissions of the file secret.log created this way, the second one, for comparison, those of the file app.log from the first example. createFile() sets the permissions when creating the file, not afterwards – there is no moment at which the file exists with the default permissions. A subsequent Files.setPosixFilePermissions() would leave this gap open.

createDirectory(), createDirectories(), createTempFile(), and createTempDirectory() take the same FileAttribute. On Windows, createFile() throws an UnsupportedOperationException when given a POSIX attribute.

Creating Directories: createDirectory() and createDirectories()

You create a single directory with Files.createDirectory(). The following example creates the directory archive in the log directory:

Path archive = logDir.resolve("archive");
Files.createDirectory(archive);
System.out.println("isDirectory(archive): " + Files.isDirectory(archive));
isDirectory(archive): true

If the directory already exists, createDirectory() throws a FileAlreadyExistsException. If the parent directory is missing, it throws a NoSuchFileException:

try {
  Files.createDirectory(archive);
} catch (FileAlreadyExistsException e) {
  System.out.println(e);
}
try {
  Files.createDirectory(logDir.resolve("archive/2026/10"));
} catch (NoSuchFileException e) {
  System.out.println(e);
}
java.nio.file.FileAlreadyExistsException: target/logs/archive
java.nio.file.NoSuchFileException: target/logs/archive/2026/10

Files.createDirectories(), in contrast, also creates all missing parent directories and throws no exception if the directory already exists. The following example creates archive/2026/10 – including 2026 – and then calls the method a second time:

Path month = logDir.resolve("archive/2026/10");
Files.createDirectories(month);
Files.createDirectories(month);
Examples.printTree(logDir);
archive/
archive/2026/
archive/2026/10/
server.log (276 bytes)

createDirectories() throws a FileAlreadyExistsException only if there is something at the path that is not a directory:

try {
  Files.createDirectories(logDir.resolve("server.log"));
} catch (FileAlreadyExistsException e) {
  System.out.println(e);
}
java.nio.file.FileAlreadyExistsException: target/logs/server.log

If createDirectories() fails, the first directories of the path may have been created anyway – the method doesn’t clean up.

I recommend createDirectories() – unless an existing directory is an error in your application logic. Then use createDirectory(), because with this method, the check and the creation are a single atomic operation: If two processes want to create the same working directory at the same time, exactly one of them succeeds, and the other one gets the FileAlreadyExistsException.

The counterparts from the old API, File.mkdir() and File.mkdirs(), return only false on any error. In the following example, archive already exists, and server.log is a file under which no directory can be created – both calls fail, but the return value doesn’t say why:

System.out.println("mkdir():  " + new File("target/logs/archive").mkdir());
System.out.println("mkdirs(): " + new File("target/logs/server.log/x").mkdirs());
mkdir():  false
mkdirs(): false

Temporary Files and Directories

For files that are needed only temporarily – e.g., an uploaded file that is no longer needed after processing – there is Files.createTempFile(). The method creates an empty file with a unique name in the system’s temporary directory:

System.out.println("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));
for (int i = 0; i < 3; i++) {
  Path tempFile = Files.createTempFile("upload-", ".part");
  System.out.println(tempFile.getFileName() + " " + Files.size(tempFile) + " bytes "
      + PosixFilePermissions.toString(Files.getPosixFilePermissions(tempFile)));
  Files.delete(tempFile);
}
java.io.tmpdir = /var/folders/wt/np9sw9515z117kn393z4t4k00000gn/T/
upload-2989293313358349324.part 0 bytes rw-------
upload-7453209811048085771.part 0 bytes rw-------
upload-15558908968731794954.part 0 bytes rw-------

The two parameters are a prefix and a suffix. Between them, createTempFile() puts a random number from a SecureRandom, as an unsigned number with up to 20 digits. The directory is the one from the system property java.io.tmpdir: on macOS a directory per account under /var/folders/, on Linux /tmp, on Windows C:\Users\<Name>\AppData\Local\Temp.

On Linux and macOS, only the account that created the file may read and write it (permissions rw-------) – even if the umask is more permissive, because the JDK sets the permissions explicitly when creating the file.

If you want the temporary file somewhere else, pass the directory as the first argument. You need that if you want to move the file into place with ATOMIC_MOVE at the end, because that works only within one file system, and the system’s temporary directory may be on a different file system than the target – more on that in the section Replacing Atomically: ATOMIC_MOVE:

Path part = Files.createTempFile(logDir, "server-", ".part");
System.out.println(part);
target/logs/server-12176482355420645255.part

You create a temporary directory with Files.createTempDirectory(). It also ends up in the directory from java.io.tmpdir, unless you pass a different one as the first argument, and it gets the permissions rwx------:

Path workDir = Files.createTempDirectory("rotation-");
System.out.println(workDir + " "
    + PosixFilePermissions.toString(Files.getPosixFilePermissions(workDir)));
/var/folders/wt/np9sw9515z117kn393z4t4k00000gn/T/rotation-955022758507380045 rwx------

Neither temporary files nor temporary directories are deleted automatically. So delete them as soon as you no longer need them – preferably in a finally block, so that this happens after an exception, too:

Path tempFile = Files.createTempFile("upload-", ".part");
try {
  Files.writeString(tempFile,
      "2026-10-17 08:15:02 INFO  Server started on port 8080\n");
  System.out.println("Written: " + Files.size(tempFile) + " bytes");
} finally {
  Files.delete(tempFile);
}
System.out.println("exists(tempFile): " + Files.exists(tempFile));
Written: 54 bytes
exists(tempFile): false

The old API has File.deleteOnExit() for this, which you can also call for a Path via tempFile.toFile().deleteOnExit(). However, the method deletes the file only when the JVM exits normally – after a crash or a kill -9, not at all – and until then, it remembers every registered path. In a server that runs for days and processes millions of uploads, every one of these files stays where it is until the next restart.

The best way to delete a temporary directory is the hand-written method deleteDirectory() from the section Deleting a Directory with Its Contents.

Copying Files with Files.copy()

Files.copy() copies a file to a new path and returns that path. The following example copies the log file into the directory archive:

Path archive = Files.createDirectory(logDir.resolve("archive"));
Path copy = Files.copy(log, archive.resolve(log.getFileName()));
System.out.println(copy + ": " + Files.size(copy) + " bytes");
target/logs/archive/server.log: 276 bytes

The second parameter is the path of the target file, not of the target directory. That is why the example appends the file name to the directory with archive.resolve(log.getFileName()). If you pass a directory instead of a file name, you get a FileAlreadyExistsException – from the point of view of copy(), something already exists at the target path, namely the directory:

try {
  Files.copy(log, archive);
} catch (FileAlreadyExistsException e) {
  System.out.println(e);
}
java.nio.file.FileAlreadyExistsException: target/logs/archive

Compared to a hand-written loop with FileInputStream and FileOutputStream, Files.copy() has two advantages: First, the call is much shorter – one line instead of a buffer, a loop, and two streams. Second, the method leaves the copying to the operating system. Since Java 20, it calls copy_file_range() on Linux, which moves the data from file to file inside the kernel without copying it into the Java process’s memory, and the library function fcopyfile() on macOS. On Windows, it uses CopyFileEx() for this. The section How Fast Is Files.copy()? shows how much difference that makes.

Copying is not atomic: If copy() throws an IOException, the target file may be incomplete. The section Replacing Atomically: ATOMIC_MOVE shows how to put a file in place so that other processes never see it half-written.

Overwriting an Existing Target File: REPLACE_EXISTING

If the target file already exists, copy() throws a FileAlreadyExistsException. With the option StandardCopyOption.REPLACE_EXISTING, the method overwrites the target file instead:

try {
  Files.copy(log, copy);
} catch (FileAlreadyExistsException e) {
  System.out.println(e);
}
Files.copy(log, copy, REPLACE_EXISTING);
System.out.println("Replaced: " + copy);
java.nio.file.FileAlreadyExistsException: target/logs/archive/server.log
Replaced: target/logs/archive/server.log

A non-empty directory cannot be replaced this way; for that, copy() throws a DirectoryNotEmptyException. If the target file is a symbolic link, copy() replaces the link, not the file it points to.

Copying Attributes: COPY_ATTRIBUTES

Without any further option, the copy gets the time of copying as its modification time. With StandardCopyOption.COPY_ATTRIBUTES, it keeps the modification time of the source file. The following example sets the modification time of the log file to the time of the last log line and then copies it without and with the option:

Files.setLastModifiedTime(log,
    FileTime.from(Instant.parse("2026-10-17T06:15:12Z")));
Path plain = Files.copy(log, archive.resolve("plain.log"));
Path withAttributes =
    Files.copy(log, archive.resolve("with-attributes.log"), COPY_ATTRIBUTES);
System.out.println("Source:          " + Files.getLastModifiedTime(log));
System.out.println("Copy:            " + Files.getLastModifiedTime(plain));
System.out.println("COPY_ATTRIBUTES: " + Files.getLastModifiedTime(withAttributes));
Source:          2026-10-17T06:15:12Z
Copy:            2026-10-25T18:13:07.733076214Z
COPY_ATTRIBUTES: 2026-10-17T06:15:12Z

Only the modification time is guaranteed to be copied. Which other attributes come along – permissions, owner, extended attributes – depends on the operating system and the file system. Without the COPY_ATTRIBUTES option, copy() doesn’t guarantee that any attributes are copied at all.

Since Java 20, copy() with COPY_ATTRIBUTES even creates a clone on macOS: Through the system call clonefile(), the original and the copy share their data blocks on APFS until one of the two files is changed. The copy then initially takes up no additional disk space, and copying takes only microseconds regardless of the file size (JDK-8293122).

If the source is a symbolic link, copy() copies the file the link points to. With LinkOption.NOFOLLOW_LINKS, it copies the link itself:

Path link = logDir.resolve("current.log");
Files.createSymbolicLink(link, Path.of("server.log"));
Path followed = Files.copy(link, archive.resolve("followed.log"));
Path notFollowed =
    Files.copy(link, archive.resolve("not-followed.log"), NOFOLLOW_LINKS);
System.out.println("isSymbolicLink(followed):    " + Files.isSymbolicLink(followed));
System.out.println("isSymbolicLink(notFollowed): "
    + Files.isSymbolicLink(notFollowed));
System.out.println("readSymbolicLink(notFollowed): "
    + Files.readSymbolicLink(notFollowed));
isSymbolicLink(followed):    false
isSymbolicLink(notFollowed): true
readSymbolicLink(notFollowed): server.log

current.log is a symbolic link to the log file server.log. The copy followed.log, created without options, is a separate file with the content of the log file. The copy not-followed.log, created with NOFOLLOW_LINKS, is a link that, like the original, points to the relative path server.log. However, a relative path in a link is relative to the directory the link is in: target/logs/current.log points to target/logs/server.log, whereas target/logs/archive/not-followed.log points to target/logs/archive/server.log. So if you copy a relative link into another directory, it points to a different file if one exists there, and nowhere otherwise.

From an InputStream to a File and From a File to an OutputStream

Not every source is a file. If the data comes from a network stream, from an archive, or from another process, for example, you have an InputStream – and for that, there is Files.copy(InputStream, Path). To get by without a network and without an external process, the following example uses an InputStream that unpacks the gzip-compressed file files/server.log.gz while reading – the unpacked data exists only in the stream, not as a file:

Path gz = Path.of("files/server.log.gz");
Path unpacked = logDir.resolve("unpacked.log");
try (InputStream in = new GZIPInputStream(Files.newInputStream(gz))) {
  long bytes = Files.copy(in, unpacked);
  System.out.println(bytes + " bytes copied");
}
276 bytes copied

The method reads the InputStream to its end and returns the number of bytes copied. It creates the target file and throws a FileAlreadyExistsException if it already exists – unless you pass REPLACE_EXISTING. It doesn’t close the InputStream; that is what the try-with-resources in the example is for.

Conversely, Files.copy(Path, OutputStream) writes a file into an OutputStream – e.g., into a network connection, into the HTTP response of a servlet, or, as here, to the console:

Files.copy(unpacked, System.out);
2026-10-17 08:15:02 INFO  Server started on port 8080
2026-10-17 08:15:07 INFO  GET /java/java-bufferedreader/ 200
2026-10-17 08:15:09 WARN  GET /java/bufferedreader/ 404
2026-10-17 08:15:11 INFO  GET /java/java-streams/ 200
2026-10-17 08:15:12 ERROR Connection reset by peer

Checking the Copy: isSameFile() and mismatch()

Files.mismatch() from Java 12 tells you whether two files have the same content. The method returns -1 if both files are identical byte for byte, and otherwise the position of the first byte that differs. If the files differ in size and the smaller one matches the larger one up to its end, mismatch() returns the size of the smaller file.

The following example compares the log file with its copy, then changes the log level of the first line in the copy from INFO to WARN, and compares again:

System.out.println("mismatch(log, copy):   " + Files.mismatch(log, copy));
System.out.println("isSameFile(log, copy): " + Files.isSameFile(log, copy));
String changed = Files.readString(copy).replaceFirst("INFO ", "WARN ");
Files.writeString(copy, changed);
System.out.println("\nAfter the change:");
System.out.println("mismatch(log, copy):   " + Files.mismatch(log, copy));
System.out.println("isSameFile(log, copy): " + Files.isSameFile(log, copy));
System.out.println("isSameFile(log, link): " + Files.isSameFile(log, link));
mismatch(log, copy):   -1
isSameFile(log, copy): false

After the change:
mismatch(log, copy):   20
isSameFile(log, copy): false
isSameFile(log, link): true

The first difference is at position 20 – that is where the log level starts in every line.

Files.isSameFile() answers a different question: whether two paths point to the same file. For the copy, the method returns false both before and after the change; for the symbolic link current.log from the section Copying Symbolic Links: NOFOLLOW_LINKS, it returns true.

If mismatch() compares two paths that point to the same file, it returns -1 without reading a single byte.

Copying a Directory with Its Contents

If you call Files.copy() on a directory, it only creates an empty directory at the target – it doesn’t copy the entries:

Path emptyCopy = Files.copy(logDir, Path.of("target/logs-copy"));
try (Stream<Path> entries = Files.list(emptyCopy)) {
  System.out.println(emptyCopy + ": " + entries.count() + " entries");
}
target/logs-copy: 0 entries

You copy a whole directory tree with Files.walkFileTree(). The method calls a method of a FileVisitor for every entry – preVisitDirectory() before each directory, visitFile() for each file, visitFileFailed() if an entry cannot be visited, and postVisitDirectory() after each directory; the article about listing directory contents shows in which order. For copying, you only need two of them: In preVisitDirectory(), you create each directory at the target, in visitFile(), you copy each file. To avoid writing the other two yourself, you extend SimpleFileVisitor. The class implements all four methods: preVisitDirectory() and visitFile() do nothing and let walkFileTree() continue, visitFileFailed() and postVisitDirectory() rethrow an IOException that occurred. You only override the two in which something is supposed to happen.

The following method copyDirectory() does exactly that:

private static void copyDirectory(Path sourceDir, Path targetDir)
      throws IOException {
  Files.walkFileTree(sourceDir, new SimpleFileVisitor<>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
          throws IOException {
      Files.createDirectories(targetDir.resolve(sourceDir.relativize(dir)));
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
          throws IOException {
      Files.copy(file, targetDir.resolve(sourceDir.relativize(file)),
            NOFOLLOW_LINKS);
      return FileVisitResult.CONTINUE;
    }
  });
}

relativize() builds the target path: For target/logs/archive/2026-10/server.log.1, sourceDir.relativize() returns the relative path archive/2026-10/server.log.1, and targetDir.resolve() appends it to the target directory:

Target path for target/logs/archive/2026-10/server.log.1: sourceDir.relativize(file) returns archive/2026-10/server.log.1, targetDir.resolve() puts target/backup in front of it.
relativize() removes the source directory from the path, resolve() puts the target directory in front of it

The option NOFOLLOW_LINKS copies a symbolic link as a link; without it, copy() would copy the file the link points to.

The following example creates two archived log files under target/logs/archive/2026-10/ and then copies the whole log directory to target/backup/:

Path month = Files.createDirectories(logDir.resolve("archive/2026-10"));
Files.copy(log, month.resolve("server.log.1"));
Files.copy(log, month.resolve("server.log.2"));

Path backup = Path.of("target/backup");
copyDirectory(logDir, backup);
Examples.printTree(backup);
archive/
archive/2026-10/
archive/2026-10/server.log.1 (276 bytes)
archive/2026-10/server.log.2 (276 bytes)
server.log (276 bytes)

If a target file already exists, copyDirectory() aborts with a FileAlreadyExistsException – as a second call shows:

try {
  copyDirectory(logDir, backup);
} catch (FileAlreadyExistsException e) {
  System.out.println(e);
}
java.nio.file.FileAlreadyExistsException: target/backup/archive/2026-10/server.log.1

With REPLACE_EXISTING as an additional argument of Files.copy() in visitFile(), the method overwrites existing files instead. The files copied up to the exception remain in any case.

The article about listing directory contents shows how to search for files with Files.walk() and Files.find().

Moving and Renaming Files and Directories with Files.move()

Files.move() moves a file to a new path. As with copy(), the second parameter is the target file, not the target directory. The following example moves the log file into the directory archive:

Path archive = Files.createDirectory(logDir.resolve("archive"));
Path archived = Files.move(log, archive.resolve(log.getFileName()));
Examples.printTree(logDir);
archive/
archive/server.log (276 bytes)

If source and target are on the same file system, move() only changes the directory entry – the data stays where it is, and the operation takes no longer for a file of 100 GB than for one of 100 bytes. If the target is on another file system, on another drive, for example, move() copies the file and then deletes the source. The following diagram shows both cases for the log file from the example:

Moving server.log from logs/ to logs/archive/: Within one file system, only the directory entry is moved, the data stays where it is. Into another file system, move() first copies the data and then deletes the source.
Within one file system, move() only moves the directory entry; into another file system, it copies the data and deletes the source

Renaming with resolveSibling()

Renaming is moving within the same directory. resolveSibling() provides the new path; it replaces the file name and keeps the directory:

Path renamed = Files.move(archived, archived.resolveSibling("server.log.1"));
Examples.printTree(logDir);
archive/
archive/server.log.1 (276 bytes)

archived.resolveSibling("server.log.1") is a shorthand for archived.getParent().resolve("server.log.1").

Moving a Directory

You move a directory just like a file. The following example renames archive with its contents to old:

Path old = Files.move(archive, logDir.resolve("old"));
Examples.printTree(logDir);
old/
old/server.log.1 (276 bytes)

Within one file system, move() only changes the directory entry here as well; the entries of the directory stay where they are. If the target is on another file system, move() would have to copy every entry individually. It doesn’t do that – for a non-empty directory, it throws an IOException instead, on Linux and macOS a DirectoryNotEmptyException.

To move a directory tree to another file system, you therefore need two steps: first copy, then delete.

Replacing an Existing Target File: REPLACE_EXISTING

If the target file already exists, move() throws a FileAlreadyExistsException. With REPLACE_EXISTING, it replaces the target file:

Files.copy(Path.of("files/server.log"), log);
Path target = old.resolve("server.log.1");
try {
  Files.move(log, target);
} catch (FileAlreadyExistsException e) {
  System.out.println(e);
}
Files.move(log, target, REPLACE_EXISTING);
Examples.printTree(logDir);
java.nio.file.FileAlreadyExistsException: target/logs/old/server.log.1
old/
old/server.log.1 (276 bytes)

The example first creates a new log file, then the first move() call fails, and the second one replaces the archived file. As with copy(), a non-empty directory cannot be replaced, and a symbolic link at the target is replaced as a link.

Replacing Atomically: ATOMIC_MOVE

If you write a file that another process reads – e.g., a configuration file or a file in a watched directory – then that process must never see it half-written. For this, you write the new version into a temporary file in the same directory and then move it into place with StandardCopyOption.ATOMIC_MOVE:

Path config = logDir.resolve("app.properties");
Files.writeString(config, "port=8080\n");
Path temp = Files.createTempFile(logDir, "app-", ".tmp");
Files.writeString(temp, "port=8443\n");
Files.move(temp, config, ATOMIC_MOVE);
System.out.print(Files.readString(config));
Examples.printTree(logDir);
port=8443
app.properties (10 bytes)
old/
old/server.log.1 (276 bytes)

With ATOMIC_MOVE, moving is a single file-system operation: Other processes see either the old or the new file under app.properties, never an intermediate state. The JDK replaces an existing target file on Linux, macOS, and Windows without you specifying REPLACE_EXISTING – move() ignores all other options together with ATOMIC_MOVE.

Moving atomically works only within one file system. If the temporary file is on another file system – in the directory from java.io.tmpdir, for example, which can be a separate file system on Linux – move() throws an AtomicMoveNotSupportedException. That is why the example creates the temporary file next to the target file with createTempFile(logDir, …).

I recommend ATOMIC_MOVE wherever another process reads the target file. A move() without this option first checks whether the target exists and then moves – in between, another process could create a file with the same name.

Deleting Files with Files.delete() and deleteIfExists()

Files.delete() deletes a file:

Files.delete(log);
System.out.println("exists(log): " + Files.exists(log));
exists(log): false

If the file doesn’t exist, delete() throws a NoSuchFileException. If you don’t want an exception in this case, use Files.deleteIfExists(). The method returns true if it deleted the file and false if the file didn’t exist:

try {
  Files.delete(log);
} catch (NoSuchFileException e) {
  System.out.println(e);
}
System.out.println("deleteIfExists(log): " + Files.deleteIfExists(log));
java.nio.file.NoSuchFileException: target/logs/server.log
deleteIfExists(log): false

delete() deletes a directory only if it is empty. Otherwise, the method throws a DirectoryNotEmptyException:

Path archive = Files.createDirectory(logDir.resolve("archive"));
Files.copy(Path.of("files/server.log"), archive.resolve("server.log.1"));
try {
  Files.delete(archive);
} catch (DirectoryNotEmptyException e) {
  System.out.println(e);
}
java.nio.file.DirectoryNotEmptyException: target/logs/archive

A symbolic link is deleted as a link; the file it points to remains:

Path link = logDir.resolve("current.log");
Files.createSymbolicLink(link, Path.of("archive/server.log.1"));
Files.delete(link);
Examples.printTree(logDir);
archive/
archive/server.log.1 (276 bytes)

On Linux and macOS, delete() also deletes a file that another process currently has open: The directory entry disappears immediately, the data only when the last process closes the file. On Windows, deleting an open file usually fails with a FileSystemException.

The counterpart from the old API, File.delete(), returns false in all of these cases:

System.out.println("File.delete(): " + new File("target/logs/archive").delete());
File.delete(): false

Deleting a Directory with Its Contents

You delete a directory with contents from the bottom up: first the files, then the empty directories. Files.walkFileTree() provides exactly this order, because it calls postVisitDirectory() only when all entries of a directory have been visited.

The following method deleteDirectory() deletes each file in visitFile() and each directory in postVisitDirectory() as soon as it is empty:

private static void deleteDirectory(Path dirToDelete) throws IOException {
  Files.walkFileTree(dirToDelete, new SimpleFileVisitor<>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
          throws IOException {
      Files.delete(file);
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc)
          throws IOException {
      if (exc != null) {
        throw exc;
      }
      Files.delete(dir);
      return FileVisitResult.CONTINUE;
    }
  });
}

If the parameter exc of postVisitDirectory() is not null, walkFileTree() could not traverse the directory completely. The implementation then rethrows the exception, because it names the cause. If it ignored exc, Files.delete() would fail with a DirectoryNotEmptyException without you finding out why the directory is not empty.

The following example creates an archived log file and a symbolic link to the current log file under archive/2026-10/ and then deletes the directory archive:

Path month = Files.createDirectories(logDir.resolve("archive/2026-10"));
Files.copy(log, month.resolve("server.log.1"));
Files.createSymbolicLink(month.resolve("latest.log"), Path.of("../../server.log"));
deleteDirectory(logDir.resolve("archive"));
Examples.printTree(logDir);
server.log (276 bytes)

The log file server.log outside the deleted directory, which the link pointed to, is still there. walkFileTree() doesn’t follow symbolic links by default, so deleteDirectory() deletes a link as a link – and not the file the link points to.

Deleting with Files.walk()

Deleting a directory with its contents is shorter with Files.walk(): You sort the paths in reverse order and then delete them one by one:

private static void deleteDirectoryWithWalk(Path dirToDelete) throws IOException {
  try (Stream<Path> paths = Files.walk(dirToDelete)) {
    paths
        .sorted(Comparator.reverseOrder())
        .forEach(
            path -> {
              try {
                Files.delete(path);
              } catch (IOException e) {
                throw new UncheckedIOException(e);
              }
            });
  }
}

The reverse sorting puts every entry before its directory: The path of a directory is a prefix of the paths of its entries and therefore comes before them in ascending order – and so after them in descending order.

However, sorted() collects all paths of the directory tree in memory before the first file is deleted – one Path object per entry. For large directory trees, I therefore recommend the variant with walkFileTree().

When the Directory Does Not Exist

If the directory doesn’t exist, both variants – deleteDirectory() and deleteDirectoryWithWalk() – throw a NoSuchFileException:

try {
  deleteDirectory(logDir.resolve("archive"));
} catch (NoSuchFileException e) {
  System.out.println(e);
}
java.nio.file.NoSuchFileException: target/logs/archive

If a missing directory should not be an error, you have to catch this exception. A check with Files.exists() beforehand is not enough: If another process deletes the directory between the check and the deletion, you get the NoSuchFileException anyway.

You create a symbolic link with Files.createSymbolicLink(). Note that you pass link and target here in the reverse order compared to copy() and move() – first the path of the link, then the path it is supposed to point to. The following example creates the link current.log to the log file:

Path link = logDir.resolve("current.log");
Files.createSymbolicLink(link, Path.of("server.log"));
System.out.println("readSymbolicLink(): " + Files.readSymbolicLink(link));
System.out.println("isSymbolicLink():   " + Files.isSymbolicLink(link));
System.out.println("size(link):         " + Files.size(link));
System.out.println("isSameFile():       " + Files.isSameFile(link, log));
readSymbolicLink(): server.log
isSymbolicLink():   true
size(link):         276
isSameFile():       true

Files.readSymbolicLink() returns the path to the target as it is stored in the link – here the relative path server.log, which the file system resolves relative to the link’s directory. All other methods follow the link: size() returns the size of the linked log file, and isSameFile() confirms that link and log file are the same file.

A hard link, in contrast, is a second directory entry for the same file. You create it with Files.createLink(), again with the link as the first argument:

Path hardLink = Files.createLink(logDir.resolve("server-hardlink.log"), log);
System.out.println("isSymbolicLink():   " + Files.isSymbolicLink(hardLink));
System.out.println("isSameFile():       " + Files.isSameFile(hardLink, log));
isSymbolicLink():   false
isSameFile():       true

The difference shows when you delete the original file:

Files.delete(log);
System.out.println("size(hardLink): " + Files.size(hardLink));
System.out.println("exists(link):   " + Files.exists(link));
size(hardLink): 276
exists(link):   false

The data remains as long as a directory entry points to it – the hard link is still a complete file with 276 bytes. The symbolic link, on the other hand, now points nowhere. A hard link must be on the same file system as the file, and it usually cannot be created for directories.

These examples work on Linux and macOS without restrictions.

How Fast Is Files.copy()?

I measured how fast Files.copy() copies with the Java Microbenchmark Harness (JMH). The test program CopyBenchmark copies a file of 100,000,000 random bytes in four ways: with Files.copy(), with FileChannel.transferTo(), with InputStream.transferTo() between the streams from Files.newInputStream() and Files.newOutputStream(), and with a hand-written loop that reads from a FileInputStream into a byte array of 8,192 bytes and writes into a FileOutputStream.

The following chart shows how long each variant takes for the whole file, in milliseconds. Files.copy() is blue, the alternatives are gray:

Copy times for a file of 100,000,000 bytes: Files.copy() 10.5 ms, FileChannel.transferTo() 9.9 ms, InputStream.transferTo() 10.0 ms, loop with byte[8192] 53.6 ms
Files.copy() copies 100,000,000 bytes in 10.5 ms, a loop with a buffer of 8,192 bytes takes 53.6 ms

Files.copy() (row 1 in the chart) takes 10.5 ms. The loop (row 4) takes 53.6 ms, a good five times as long. It calls the operating system about 12,200 times each for reading and for writing, and on every call, the JDK copies the block between a buffer of its own and the byte array. Files.copy(), in contrast, hands the whole file to fcopyfile() in a single call.

The two transferTo() variants (rows 2 and 3) are even slightly faster than Files.copy(), at 9.9 and 10.0 ms. FileChannel.transferTo() first tries to let the operating system write the data directly to the target – on Linux with copy_file_range() or sendfile(), on macOS with sendfile(). On macOS, however, that writes only to sockets, not to files. For a target file, the JDK therefore maps the source file into memory in sections of up to 8 MiB and writes it from there into the target file. InputStream.transferTo() ends up in the same code, because the streams from Files.newInputStream() and Files.newOutputStream() pass the call on to their FileChannel objects.

With COPY_ATTRIBUTES, Files.copy() creates a clone on APFS, as the section Copying Attributes: COPY_ATTRIBUTES shows. The program CloneSizeCheck measures a median between 0.10 and 0.11 ms for it – for a file of 1,000,000 bytes just as for one of 1,000,000,000 bytes. The chart doesn’t show the clone, because its bar would hardly be visible.

I recommend Files.copy() for every copy from file to file: It is almost as fast as transferTo(), takes only one line, and with COPY_ATTRIBUTES, it copies no data at all on APFS. I haven’t measured on Linux and Windows; there, Files.copy() and transferTo() work with other system calls, and the differences may be larger or smaller.

Common Mistakes

The sections above show each of the following mistakes in detail:

  • The target directory instead of the target file: Files.copy(file, dir) and Files.move(file, dir) throw a FileAlreadyExistsException, because something already exists at the target path – the directory. The correct target is dir.resolve(file.getFileName()).
  • First exists(), then createFile(): Between the check and the creation, another process can create the file. createFile() checks by itself, atomically.
  • !Files.exists(file) as “the file is missing”: Without access permissions, exists() and notExists() both return false.
  • Files.copy() on a directory: It creates only an empty directory; to copy the entries, you need walkFileTree().
  • Files.delete() on a full directory: The method throws a DirectoryNotEmptyException; you have to delete from the bottom up.
  • ATOMIC_MOVE from the temp directory: If the temporary file is on another file system, move() throws an AtomicMoveNotSupportedException. It’s best to put the temporary file next to the target file.
  • File.renameTo(), File.delete(), File.mkdirs() without checking the return value: The methods report errors only with false. If you don’t check the return value, the error goes unnoticed.
  • deleteOnExit() for files of a long-running server: The files stay until the restart.

Summary

The Files class creates, copies, moves, and deletes files and directories – with one method call each, which throws an exception with the path and the cause in case of an error. The methods of File, in contrast, return false in case of an error.

createFile(), createDirectory(), and delete() check by themselves whether their preconditions are met, and they do so atomically. A check with exists() beforehand can lead to a race condition: In the example with two threads, the check was already outdated 8,114 times out of 10,000 before the operation following the check ran. Moreover, exists() and notExists() are not opposites – if the operating system cannot answer the question, both return false.

copy() and move() expect the file as the target, not the directory. Both replace an existing target file only with REPLACE_EXISTING, and both treat a directory as a single entry: copy() creates an empty directory, move() renames it within one file system and refuses a full directory across file system boundaries. For whole directory trees – copying, deleting – Files.walkFileTree() is the tool.

My recommendations:

  • Use Files instead of File; you convert a File object from an older API with toPath().
  • Call the operation and catch the exception instead of checking with exists() beforehand. exists() and notExists() are for decisions in which a race condition cannot do any damage.
  • Create directories with createDirectories() – and with createDirectory() if an existing directory is an error in your application logic.
  • Delete temporary files in a finally block, not with deleteOnExit().
  • Specify COPY_ATTRIBUTES if the copy should keep the modification time – on macOS, it is then a clone.
  • Write files that others read into a temporary file in the same directory and move it with ATOMIC_MOVE.
  • Delete directory trees with walkFileTree(); the variant with walk() and sorted() keeps all paths in memory.

The articles about reading files and writing files show how to read and write a file. The article about file and directory names with File, Path, and Paths shows how to construct file and directory paths with Path. The overview of Java file I/O shows all articles on files in Java, arranged by task.

Did you take something away from this article? With a review on my ProvenExpert profile, you help other developers assess whether these articles are worth reading – and you help me understand which content is most useful to you.

👉 Leave a review

Want Even More Knowledge?

My blog features many articles on Java, software architecture, and performance — from foundational concepts to advanced patterns.

If you want to go deeper, check out my trainings: hands-on, easy to understand, and directly applicable to your day-to-day project work. Instead of theory, I teach principles that help you write code that is better, more maintainable, and more performant in the long run.

Explore the Java Trainings

Become a Better Java Developer

My free newsletter keeps you ahead. Modern Java: new versions & features, performance, and JVM insights – once a month.

Search