Video in progress

Strong Junior 📁 IO and NIO

Which options do you need to know when using Files.copy and Files.move?

By default, both throw FileAlreadyExistsException if the target file exists; to overwrite you need REPLACE_EXISTING. For move, ATOMIC_MOVE never leaves a half-moved file, and for copy, COPY_ATTRIBUTES also copies timestamps and permissions.

📖 Answer

Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

Files.move(tmp, finalPath,
        StandardCopyOption.REPLACE_EXISTING,
        StandardCopyOption.ATOMIC_MOVE);

Within one disk (file system), move usually just renames: fast and atomic. Between two different disks it actually copies and then deletes. In that case, if ATOMIC_MOVE was given, you get AtomicMoveNotSupportedException, which is good, because it won't quietly do a non-atomic move on you.

Practical nuances:

  • there is also Files.copy(InputStream, Path), handy for writing data coming from HTTP straight to a file;
  • if you copy a directory, only an empty directory is created; its contents are not copied;
  • in Docker, /tmp and a volume are often different file systems, which is the answer to "why did move become slow".

Atomic move matters for file uploads: if another process is watching the directory, it never sees a half-written file.