Skip to lesson

Copy and move files with options

Files.copy makes a second file with the same bytes; Files.move puts a file at a new path and removes the old one. Small option flags decide what happens when the target already exists, whether the file's date is kept, and whether the move happens in one safe step.

Files.copy and Files.move

Files.copy(source, target) copies the file at source to target and returns target. Files.move(source, target) does the same, but the source is gone afterwards.

By default both are careful. If target already exists, they throw FileAlreadyExistsException and change nothing. If source is missing, they throw NoSuchFileException.

Example 1 · Copy, then move

CopyMoveDemo.javaJava
import java.io.IOException;import java.nio.file.FileAlreadyExistsException;import java.nio.file.Files;import java.nio.file.Path;
public class CopyMoveDemo {    public static void main(String[] args) throws IOException {        Path marks = Path.of("marks.csv");        Files.writeString(marks, "Roll,Marks\n21,88\n22,91");
        Path backup = Files.copy(marks, Path.of("marks-backup.csv"));        System.out.println("Copied to " + backup.getFileName());        System.out.println("Both exist? " + Files.exists(marks) + " " + Files.exists(backup));        System.out.println("Same bytes? " + (Files.mismatch(marks, backup) == -1));
        try {            Files.copy(marks, backup);        } catch (FileAlreadyExistsException e) {            System.out.println("Copy again: " + e.getFile() + " already exists");        }
        Path moved = Files.move(backup, Path.of("old-marks.csv"));        System.out.println("Moved to " + moved.getFileName());        System.out.println("Backup still there? " + Files.exists(backup));
        Files.delete(marks);        Files.delete(moved);    }}
Output
Copied to marks-backup.csv
Both exist? true true
Same bytes? true
Copy again: marks-backup.csv already exists
Moved to old-marks.csv
Backup still there? false

What this code does

  • Files.mismatch(a, b) (Java 12) returns the position of the first different byte, or -1 when the files are the same, so it is a quick way to check a copy.
  • Without options, a second copy refuses to overwrite the target. After move, the old name no longer exists: the file lives only at the new path.

Copying a folder copies only the folder itself, empty: the files inside are not copied. Copying a whole tree needs a walk over every file, which the Copy or delete a whole folder tree lesson covers.

REPLACE_EXISTING, COPY_ATTRIBUTES and ATOMIC_MOVE

Both methods take extra options from the enum StandardCopyOption, listed after the target: Files.copy(a, b, StandardCopyOption.REPLACE_EXISTING).

Example 2 · REPLACE_EXISTING and COPY_ATTRIBUTES

CopyOptionsDemo.javaJava
import java.io.IOException;import java.nio.file.FileAlreadyExistsException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;import java.nio.file.attribute.FileTime;import java.time.Instant;
public class CopyOptionsDemo {    public static void main(String[] args) throws IOException {        Path latest = Path.of("timetable.txt");        Path shared = Path.of("timetable-shared.txt");        Files.writeString(latest, "Mon: DBMS lab");        Files.writeString(shared, "Mon: holiday");     // an old copy
        try {            Files.copy(latest, shared);        } catch (FileAlreadyExistsException e) {            System.out.println("No option: " + e.getClass().getSimpleName());        }
        Files.copy(latest, shared, StandardCopyOption.REPLACE_EXISTING);        System.out.println("REPLACE_EXISTING, same content? " + (Files.mismatch(latest, shared) == -1));
        FileTime examDay = FileTime.from(Instant.parse("2025-03-10T04:30:00Z"));        Files.setLastModifiedTime(latest, examDay);        Files.copy(latest, shared, StandardCopyOption.REPLACE_EXISTING,                StandardCopyOption.COPY_ATTRIBUTES);        System.out.println("COPY_ATTRIBUTES, same time? " + Files.getLastModifiedTime(shared).equals(examDay));
        Files.delete(latest);        Files.delete(shared);    }}
Output
No option: FileAlreadyExistsException
REPLACE_EXISTING, same content? true
COPY_ATTRIBUTES, same time? true

What this code does

  • REPLACE_EXISTING lets the copy overwrite the old timetable-shared.txt. Several options can be passed together, separated by commas.
  • setLastModifiedTime gives the source a fixed date (the next lesson covers file times). With COPY_ATTRIBUTES the copy gets the same date on every system; without it, Linux and macOS would show the time of the copy.

Example 3 · ATOMIC_MOVE: replace a settings file in one step

AtomicMoveDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;
public class AtomicMoveDemo {    public static void main(String[] args) throws IOException {        Path settings = Path.of("settings.txt");        Files.writeString(settings, "theme=light");
        Path temp = Path.of("settings.txt.tmp");        Files.writeString(temp, "theme=dark\nlanguage=hi");        Files.move(temp, settings, StandardCopyOption.ATOMIC_MOVE);
        System.out.println("settings.txt now:");        System.out.println(Files.readString(settings));        System.out.println("Temp file left? " + Files.exists(temp));
        Files.delete(settings);    }}
Output
settings.txt now:
theme=dark
language=hi
Temp file left? false

What this code does

  • The new settings are written to a temporary file first. If the program crashes while writing, settings.txt is still the old, complete file.
  • ATOMIC_MOVE then swaps the new file in as one step, so another program never reads half a file. Files.readString reads the whole file as text; the Reading and Writing Text Files module covers it.
  • REPLACE_EXISTING: overwrite the target if it exists. Use it only when losing the old target is fine.
  • COPY_ATTRIBUTES (copy): give the copy the source's attributes, at least its last-modified time. Without it, Linux and macOS give the copy the current time.
  • ATOMIC_MOVE (move): do the move as one step, so other programs see either the old state or the new one, never a half-done file.
With ATOMIC_MOVE, Java ignores the other options. Whether it replaces an existing target is left to the system; Windows, macOS and Linux replace it.

Renaming is a move

Java has no separate rename method. A rename is a move to a new name in the same folder: Files.move(file, file.resolveSibling("new-name.txt")).

Example 4 · Renaming fest photos

RenameDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
public class RenameDemo {    public static void main(String[] args) throws IOException {        Path folder = Files.createDirectories(Path.of("fest-photos"));        List<String> cameraNames = List.of("IMG_0041.jpg", "IMG_0042.jpg", "IMG_0043.jpg");        for (String n : cameraNames) {            Files.createFile(folder.resolve(n));        }
        List<Path> renamed = new ArrayList<>();        int number = 1;        for (String n : cameraNames) {            Path old = folder.resolve(n);            Path target = Files.move(old, old.resolveSibling("fest-2025-" + number + ".jpg"));            renamed.add(target);            System.out.println(n + " -> " + target.getFileName());            number++;        }        System.out.println("Old name gone? " + Files.notExists(folder.resolve("IMG_0041.jpg")));
        for (Path p : renamed) {            Files.delete(p);        }        Files.delete(folder);    }}
Output
IMG_0041.jpg -> fest-2025-1.jpg
IMG_0042.jpg -> fest-2025-2.jpg
IMG_0043.jpg -> fest-2025-3.jpg
Old name gone? true

What this code does

  • old.resolveSibling(newName) keeps the folder and changes only the name, so Files.move acts as a rename.
  • move returns the new path, which is kept for the clean-up. The camera's old names no longer exist.

On the same drive this is fast, whatever the file size: the system only changes the name in the folder's list and does not copy any bytes. The same rules apply as for any move: the new name must be free unless you pass REPLACE_EXISTING.

On Windows, a rename that changes only the case, such as Photo.JPG to Photo.jpg, can leave the name unchanged, because Windows sees the same file. Rename through a temporary name in two steps.

Moving across drives and partitions

A file store is one storage area the system manages on its own, such as drive C:, drive D:, a pen drive or a Linux partition. Files.getFileStore(path) tells you which one a path is on.

Example 5 · Atomic move with a fallback for other drives

MoveSafelyDemo.javaJava
import java.io.IOException;import java.nio.file.AtomicMoveNotSupportedException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;
public class MoveSafelyDemo {    static String moveSafely(Path source, Path target) throws IOException {        try {            Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);            return "atomic move";        } catch (AtomicMoveNotSupportedException e) {            Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);            return "copy, then delete (different drive)";        }    }
    public static void main(String[] args) throws IOException {        Path report = Files.writeString(Path.of("report.pdf"), "sem 5 report");        Path archive = Files.createDirectories(Path.of("archive"));
        boolean sameStore = Files.getFileStore(report).equals(Files.getFileStore(archive));        System.out.println("Same file store? " + sameStore);
        Path target = archive.resolve("report.pdf");        System.out.println("Used: " + moveSafely(report, target));        System.out.println("In archive? " + Files.exists(target));
        Files.delete(target);        Files.delete(archive);    }}
Output
Same file store? true
Used: atomic move
In archive? true

What this code does

  • Both paths are on the same drive, so ATOMIC_MOVE works. With a target on another drive, it would throw AtomicMoveNotSupportedException and the fallback would copy the bytes and delete the source.
  • Catching that one exception keeps the safe, one-step move whenever it is possible and still finishes the job when it is not. Files.writeString returns the path it wrote, which is why it can sit on the right of =.

Inside one file store, a move is a quick rename. Across file stores, Java must copy the bytes and then delete the source. That takes time for big files, and it is not one safe step: a crash halfway can leave both files, or a half-written target. So ATOMIC_MOVE across drives throws AtomicMoveNotSupportedException (on Windows: "The system cannot move the file to a different disk drive"). A folder that is not empty cannot be moved across drives with one Files.move either; it throws an IOException, and you copy the tree and then delete the old one.

Next step

Check your understanding

11 quick questions